ectly与Swagger一起设置版本控制,请参见:https://stackoverflow.com/questions/60084877/swagger-not-finding-apiversion-ed-actions #端区 //通过Swashback添加开放式API(招摇过市)功能——有关完整选项,请参阅:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md#configuration--定制 //提示:向操作添加三重斜杠注释///可以通过向节标题添加描述来增强招摇过市UI。 //提示:将元素添加到创建操作方法文档中。它补充了元素中指定的信息,并提供了更健壮的招摇过市UI。元素内容可以由文本、JSON或XML组成。 services.AddSwaggerGen(c=>//配置文档--请参阅:https://docs.microsoft.com/en-us/samples/aspnet/aspnetcore.docs/getstarted-swashbuckle-aspnetcore/?tabs=visual-工作室 { //将swagger配置为处理版本控制,否则会出现此错误:“规范中未定义任何操作!” c、 DocInclusionPredicate((docName,apiDesc)=> { 如果(!apiDesc.TryGetMethodInfo(out MethodInfo MethodInfo)) { 返回false; } IEnumerable versions=methodInfo.DeclaringType .GetCustomAttributes(true) 第()类 .SelectMany(a=>a.Versions); 返回versions.Any(v=>$“v{v.ToString()}”==docName); }); c、 SwaggerDoc(“v1.0”,新OpenApiInfo { Version=“v1.0”, Title=“测试软件blah API 1.0版”, Description=“用于访问和管理blah度量报告的RESTful web API。”, TermsOfService=新Uri(“https://test.com/termsofservice"), Contact=newopenapicontact { Name=“测试软件”, 电子邮件=”support@test.com", Url=新Uri(“https://test.com/apisupport"), }, 许可证=新的OpenAPI许可证 { Name=“使用许可证:CDDL-1.0”, Url=新Uri(“https://opensource.org/licenses/CDDL-1.0"), } }); c、 SwaggerDoc(“v2.0”,新OpenApiInfo { Version=“v2.0”, Title=“测试软件blah API 2.0版”, Description=“用于访问和管理blah度量报告的RESTful web API。”, TermsOfService=新Uri(“https://test.com/termsofservice"), Contact=newopenapicontact { Name=“测试软件”, 电子邮件=”support@test.com", Url=新Uri(“https://test.com/apisupport"), }, 许可证=新的OpenAPI许可证 { Name=“使用许可证:CDDL-1.0”, Url=新Uri(“https://opensource.org/licenses/CDDL-1.0"), } }); //为swagger应用API版本控制过滤器 //c、 操作过滤器(); //c、 DocumentFilter(); c、 EnableAnnotations(); c、 示例过滤器(); c、 OperationFilter(“correlationId”,“请求的相关Id”,false);//将您喜欢的任何字符串添加到请求头中—在本例中,是一个相关Id c、 OperationFilter();//[SwaggerResponseHeader] //为Swagger JSON和UI设置注释路径。 var xmlFile=$“{Assembly.getExecutionGassembly().GetName().Name}.xml”; var xmlPath=Path.Combine(AppContext.BaseDirectory,xmlFile); c、 includexmlcoments(xmlPath);//标准Swashbuckle功能,这需要在c.OperationFilter()之前完成 c、 OperationFilter();//将“(Auth)”添加到摘要中,以便查看哪些端点具有授权 //或使用通用方法,例如c.OperationFilter(); //为OAuth2的每个操作添加安全信息 c、 操作过滤器(); //或使用通用方法,例如c.OperationFilter(); //如果您使用的是SecurityRequirementsOperationFilter,还需要告诉Swashback您使用的是OAuth2 c、 AddSecurityDefinition(“oauth2”,新的OpenApiSecurityScheme { Description=“使用承载方案的标准授权标头。示例:\“承载{token}\”, In=参数位置.Header, Name=“授权”, 类型=SecuritySchemeType.ApiKey }); }); services.addswaggerExamplesFromAssembly(Assembly.GetEntryAssembly());//这将向服务提供商注册您的“示例”。 #端区 //使中间件能够将生成的Swagger作为JSON端点提供服务。 app.UseSwagger(); //允许中间件为swagger ui(HTML、JS、CSS等)提供服务,并指定swagger JSON端点。 app.UseSwaggerUI(c=> { c、 SwaggerEndpoint(“/swagger/v1.0/swagger.json”,“测试API v1.0”); c、 SwaggerEndpoint(“/swagger/v2.0/swagger.json”,“测试API v2.0”); });
已解决!好的 信用卡应转到,此处的评论 秘方是: a、 )使用MapToApiVersion-Swagger属性装饰控制器的操作方法。。。例如:ectly与Swagger一起设置版本控制,请参见:https://stackoverflow.com/questions/60084877/swagger-not-finding-apiversion-ed-actions #端区 //通过Swashback添加开放式API(招摇过市)功能——有关完整选项,请参阅:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md#configuration--定制 //提示:向操作添加三重斜杠注释///可以通过向节标题添加描述来增强招摇过市UI。 //提示:将元素添加到创建操作方法文档中。它补充了元素中指定的信息,并提供了更健壮的招摇过市UI。元素内容可以由文本、JSON或XML组成。 services.AddSwaggerGen(c=>//配置文档--请参阅:https://docs.microsoft.com/en-us/samples/aspnet/aspnetcore.docs/getstarted-swashbuckle-aspnetcore/?tabs=visual-工作室 { //将swagger配置为处理版本控制,否则会出现此错误:“规范中未定义任何操作!” c、 DocInclusionPredicate((docName,apiDesc)=> { 如果(!apiDesc.TryGetMethodInfo(out MethodInfo MethodInfo)) { 返回false; } IEnumerable versions=methodInfo.DeclaringType .GetCustomAttributes(true) 第()类 .SelectMany(a=>a.Versions); 返回versions.Any(v=>$“v{v.ToString()}”==docName); }); c、 SwaggerDoc(“v1.0”,新OpenApiInfo { Version=“v1.0”, Title=“测试软件blah API 1.0版”, Description=“用于访问和管理blah度量报告的RESTful web API。”, TermsOfService=新Uri(“https://test.com/termsofservice"), Contact=newopenapicontact { Name=“测试软件”, 电子邮件=”support@test.com", Url=新Uri(“https://test.com/apisupport"), }, 许可证=新的OpenAPI许可证 { Name=“使用许可证:CDDL-1.0”, Url=新Uri(“https://opensource.org/licenses/CDDL-1.0"), } }); c、 SwaggerDoc(“v2.0”,新OpenApiInfo { Version=“v2.0”, Title=“测试软件blah API 2.0版”, Description=“用于访问和管理blah度量报告的RESTful web API。”, TermsOfService=新Uri(“https://test.com/termsofservice"), Contact=newopenapicontact { Name=“测试软件”, 电子邮件=”support@test.com", Url=新Uri(“https://test.com/apisupport"), }, 许可证=新的OpenAPI许可证 { Name=“使用许可证:CDDL-1.0”, Url=新Uri(“https://opensource.org/licenses/CDDL-1.0"), } }); //为swagger应用API版本控制过滤器 //c、 操作过滤器(); //c、 DocumentFilter(); c、 EnableAnnotations(); c、 示例过滤器(); c、 OperationFilter(“correlationId”,“请求的相关Id”,false);//将您喜欢的任何字符串添加到请求头中—在本例中,是一个相关Id c、 OperationFilter();//[SwaggerResponseHeader] //为Swagger JSON和UI设置注释路径。 var xmlFile=$“{Assembly.getExecutionGassembly().GetName().Name}.xml”; var xmlPath=Path.Combine(AppContext.BaseDirectory,xmlFile); c、 includexmlcoments(xmlPath);//标准Swashbuckle功能,这需要在c.OperationFilter()之前完成 c、 OperationFilter();//将“(Auth)”添加到摘要中,以便查看哪些端点具有授权 //或使用通用方法,例如c.OperationFilter(); //为OAuth2的每个操作添加安全信息 c、 操作过滤器(); //或使用通用方法,例如c.OperationFilter(); //如果您使用的是SecurityRequirementsOperationFilter,还需要告诉Swashback您使用的是OAuth2 c、 AddSecurityDefinition(“oauth2”,新的OpenApiSecurityScheme { Description=“使用承载方案的标准授权标头。示例:\“承载{token}\”, In=参数位置.Header, Name=“授权”, 类型=SecuritySchemeType.ApiKey }); }); services.addswaggerExamplesFromAssembly(Assembly.GetEntryAssembly());//这将向服务提供商注册您的“示例”。 #端区 //使中间件能够将生成的Swagger作为JSON端点提供服务。 app.UseSwagger(); //允许中间件为swagger ui(HTML、JS、CSS等)提供服务,并指定swagger JSON端点。 app.UseSwaggerUI(c=> { c、 SwaggerEndpoint(“/swagger/v1.0/swagger.json”,“测试API v1.0”); c、 SwaggerEndpoint(“/swagger/v2.0/swagger.json”,“测试API v2.0”); });,configuration,swagger,versioning,webapi,asp.net-core-5.0,Configuration,Swagger,Versioning,Webapi,Asp.net Core 5.0,已解决!好的 信用卡应转到,此处的评论 秘方是: a、 )使用MapToApiVersion-Swagger属性装饰控制器的操作方法。。。例如:[MapToApiVersion(“1.0”)] b、 )确保DocInclusionPredite lambda的设置如下: setup.DocInclusionPredicate((version, desc) => { if (!desc.TryGetMethodInf
[MapToApiVersion(“1.0”)]
b、 )确保DocInclusionPredite lambda的设置如下:
setup.DocInclusionPredicate((version, desc) =>
{
if (!desc.TryGetMethodInfo(out MethodInfo methodInfo))
return false;
var versions = methodInfo.DeclaringType
.GetCustomAttributes(true)
.OfType<ApiVersionAttribute>()
.SelectMany(attr => attr.Versions);
var maps = methodInfo
.GetCustomAttributes(true)
.OfType<MapToApiVersionAttribute>()
.SelectMany(attr => attr.Versions)
.ToArray();
return versions.Any(v => $"v{v.ToString()}" == version)
&& (!maps.Any() || maps.Any(v => $"v{v.ToString()}" == version));
});
setup.DocInclusionPredicate((版本,描述)=>
{
如果(!desc.TryGetMethodInfo(out MethodInfo MethodInfo))
返回false;
var versions=methodInfo.DeclaringType
.GetCustomAttributes(true)
// NOTE: declaration order matters for versioning APIs to be setup correctly
services.AddVersionedApiExplorer(o => // this is required to support swagger gathering info on all of the existing endpoints for ALL versions of APIs
{
o.GroupNameFormat = "'v'VVV";
o.SubstituteApiVersionInUrl = true;
});
services.AddApiVersioning(o =>
{
o.ReportApiVersions = true;
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(1, 0);
});
#endregion
#region Swagger Setup Region
#region Swashbuckle Overview - an automated Swagger content generator -- See: https://github.com/domaindrivendev/Swashbuckle.WebApi
// Seamlessly adds a Swagger to WebApi projects! Combines ApiExplorer and Swagger/ swagger - ui to provide a rich discovery, documentation and playground experience
// to your API consumers.
// In addition to its Swagger generator, Swashbuckle also contains an embedded version of swagger - ui which it will automatically serve up once Swashbuckle is installed.
// This means you can complement your API with a slick discovery UI to assist consumers with their integration efforts.Best of all, it requires minimal coding and maintenance,
// allowing you to focus on building an awesome API!
// And that's not all ...
// Once you have a Web API that can describe itself in Swagger, you've opened the treasure chest of Swagger-based tools including a client generator that can be targeted to a wide
// range of popular platforms. See swagger-codegen for more details.
//
// Features:
// Auto-generated Swagger 2.0
// * Seamless integration of swagger-ui
// * Reflection - based Schema generation for describing API types
// * Extensibility hooks for customizing the generated Swagger doc
// * Extensibility hooks for customizing the swagger - ui
// * Out - of - the - box support for leveraging Xml comments
// * Support for describing ApiKey, Basic Auth and OAuth2 schemes... including UI support for the Implicit OAuth2 flow
//
// How does Swashbuckle find the endpoints that it needs to document?...
// Swashbuckle requires the use of routing attributes to find the endpoints... if you are using conventional routing (as opposed to attribute routing), any controllers and the actions
// on those controllers that use conventional routing will not be represented in ApiExplorer, which means Swashbuckle won't be able to find those controllers
// and generate Swagger operations from them. For example:
//
// [Route("example")]
// public class ExampleController : Controller
//
// IMPORTANT: Ensure your API actions and parameters are decorated with explicit "Http" and "From" bindings.
// [HttpPost]
// public void CreateProduct([FromBody] Product product)
// ...
// [HttpGet]
// public IEnumerable<Product> SearchProducts([FromQuery] string keywords)
// NOTE: If you omit the explicit parameter bindings, the generator will describe them as "query" params by default.
// TIP: to correctly setup versioning in conjunction with Swagger, see: https://stackoverflow.com/questions/60084877/swagger-not-finding-apiversion-ed-actions
#endregion
// Add Open API (Swagger) functionality via Swashbuckle -- for full options, see: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md#configuration--customization
// TIP: Adding triple-slash comments /// to an action enhances the Swagger UI by adding the description to the section header.
// TIP: Add a <remarks> element to the Create action method documentation. It supplements information specified in the <summary> element and provides a more robust Swagger UI. The <remarks> element content can consist of text, JSON, or XML.
services.AddSwaggerGen(c => // Configuration documentation -- See: https://docs.microsoft.com/en-us/samples/aspnet/aspnetcore.docs/getstarted-swashbuckle-aspnetcore/?tabs=visual-studio
{
// configure swagger to handle versioning, otherwise this error is presented: "No operations defined in spec!"
c.DocInclusionPredicate((docName, apiDesc) =>
{
if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo))
{
return false;
}
IEnumerable<ApiVersion> versions = methodInfo.DeclaringType
.GetCustomAttributes(true)
.OfType<ApiVersionAttribute>()
.SelectMany(a => a.Versions);
return versions.Any(v => $"v{v.ToString()}" == docName);
});
c.SwaggerDoc("v1.0", new OpenApiInfo
{
Version = "v1.0",
Title = "test Software blah API version 1.0",
Description = "A RESTful web API to access and manage blah metric reporting.",
TermsOfService = new Uri("https://test.com/termsofservice"),
Contact = new OpenApiContact
{
Name = "test Software",
Email = "support@test.com",
Url = new Uri("https://test.com/apisupport"),
},
License = new OpenApiLicense
{
Name = "Use License: CDDL-1.0",
Url = new Uri("https://opensource.org/licenses/CDDL-1.0"),
}
});
c.SwaggerDoc("v2.0", new OpenApiInfo
{
Version = "v2.0",
Title = "test Software blah API Version 2.0",
Description = "A RESTful web API to access and manage blah metric reporting.",
TermsOfService = new Uri("https://test.com/termsofservice"),
Contact = new OpenApiContact
{
Name = "test Software",
Email = "support@test.com",
Url = new Uri("https://test.com/apisupport"),
},
License = new OpenApiLicense
{
Name = "Use License: CDDL-1.0",
Url = new Uri("https://opensource.org/licenses/CDDL-1.0"),
}
});
// Apply the API versioning filters for swagger
//c.OperationFilter<SwaggerRemoveVersionFromParameter>();
//c.DocumentFilter<SwaggerReplaceVersionWithExactValueInPath>();
c.EnableAnnotations();
c.ExampleFilters();
c.OperationFilter<AddHeaderOperationFilter>("correlationId", "Correlation Id for the request", false); // adds any string you like to the request headers - in this case, a correlation id
c.OperationFilter<AddResponseHeadersFilter>(); // [SwaggerResponseHeader]
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath); // standard Swashbuckle functionality, this needs to be before c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>()
c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); // Adds "(Auth)" to the summary so that you can see which endpoints have Authorization
// or use the generic method, e.g. c.OperationFilter<AppendAuthorizeToSummaryOperationFilter<MyCustomAttribute>>();
// add Security information to each operation for OAuth2
c.OperationFilter<SecurityRequirementsOperationFilter>();
// or use the generic method, e.g. c.OperationFilter<SecurityRequirementsOperationFilter<MyCustomAttribute>>();
// if you're using the SecurityRequirementsOperationFilter, you also need to tell Swashbuckle you're using OAuth2
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
});
services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly()); // This will register your "examples" with the ServiceProvider.
#endregion
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "test API v1.0");
c.SwaggerEndpoint("/swagger/v2.0/swagger.json", "test API v2.0");
});
setup.DocInclusionPredicate((version, desc) =>
{
if (!desc.TryGetMethodInfo(out MethodInfo methodInfo))
return false;
var versions = methodInfo.DeclaringType
.GetCustomAttributes(true)
.OfType<ApiVersionAttribute>()
.SelectMany(attr => attr.Versions);
var maps = methodInfo
.GetCustomAttributes(true)
.OfType<MapToApiVersionAttribute>()
.SelectMany(attr => attr.Versions)
.ToArray();
return versions.Any(v => $"v{v.ToString()}" == version)
&& (!maps.Any() || maps.Any(v => $"v{v.ToString()}" == version));
});