.NET Core3.0 WebAPI 集成 Swagger 5.0

来自:cqinwn

在项目中引用Swashbuckle.AspNetCore和Swashbuckle.AspNetCore.Filters两个dll,在Startup中的ConfigureServices相关配置代码如下


services.AddSwaggerGen(options =>
{
   string contactName = Configuration.GetSection("SwaggerDoc:ContactName").Value;
   string contactNameEmail = Configuration.GetSection("SwaggerDoc:ContactEmail").Value;
   string contactUrl = Configuration.GetSection("SwaggerDoc:ContactUrl").Value;
   options.SwaggerDoc("v1", new OpenApiInfo
   {
       Version = Configuration.GetSection("SwaggerDoc:Version").Value,
       Title = Configuration.GetSection("SwaggerDoc:Title").Value,
       Description = Configuration.GetSection("SwaggerDoc:Description").Value,
       Contact = new OpenApiContact { Name = contactName, Email = contactNameEmail, Url =new Uri(contactUrl)},
       License = new OpenApiLicense { Name = contactName, Url = new Uri(contactUrl) }
   });

   var basePath = PlatformServices.Default.Application.ApplicationBasePath;
   var xmlPath = Path.Combine(basePath, "Yuebon.WebApi.xml");
   options.IncludeXmlComments(xmlPath);
   options.DocumentFilter<HiddenApiFilter>(); // 在接口类、方法标记属性 [HiddenApi],可以阻止【Swagger文档】生成
   options.OperationFilter<AddHeaderOperationFilter>("correlationId", "Correlation Id for the request", false); // adds any string you like to the request headers - in this case, a correlation id
   options.OperationFilter<AddResponseHeadersFilter>();
options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
   options.OperationFilter<SecurityRequirementsOperationFilter>();
   //给api添加token令牌证书
   options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
   {
       Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
       Name = "Authorization",//jwt默认的参数名称
       In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
       Type = SecuritySchemeType.ApiKey
   });
});


两个重点:


1、options.DocumentFilter<HiddenApiFilter>();定义那些接口方法被隐藏


2、启用oauth2安全授权访问api接口


options.OperationFilter<SecurityRequirementsOperationFilter>();
//给api添加token令牌证书
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
   Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
   Name = "Authorization",//jwt默认的参数名称
   In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
   Type = SecuritySchemeType.ApiKey
});


其中使用SecurityRequirementsOperationFilter需要在控制器头部加[Authorization]或则方法头部加[Authorization],如下:


[Authorize]
public class TokenController : ControllerBase


或者

[Authorize("Customer")]
public PersonResponse GetPerson([FromBody]PersonRequest personRequest)


这样在每个接口才会有小锁出现。



更多介绍请参考https://github.com/domaindrivendev/Swashbuckle.AspNetCore和https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters

推荐↓↓↓
DotNet程序员
上一篇:ASP.NET Core 使用IHttpClientFactory发出HTTP请求 下一篇:.NET Core微服务 权限系统+工作流(二)工作流系统