1:提前添加:程序集 Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a
2:在 Startup 的 ConfigureServices中添加如下:
//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Title = $"ERP接口",
Version = "v1",
options.CustomSchemaIds(type => type.FullName); // 解决相同类名会报错的问题
//var basePath = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath;
//var xmlPathModel = System.IO.Path.Combine(basePath, $"Ledao.Application.xml");
//var xmlPath = System.IO.Path.Combine(basePath, $"Ledao.Web.xml");
// options.IncludeXmlComments(xmlPathModel);
//options.IncludeXmlComments(xmlPath);
//过滤
options.DocumentFilter<ApplyTagDescriptions>();//添加对控制器的标签(描述)
options.OperationFilter<SwaggerTokenFilter>(); //Token
});
3:在Configure下添加使用:
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
4:处理授权:
public class SwaggerTokenFilter : IOperationFilter
{
/// <summary>
///
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(Operation operation, OperationFilterContext context)
{
// IOperationFilter
operation.Parameters = operation.Parameters ?? new List<IParameter>();
foreach (var item in context.ApiDescription.ControllerAttributes())
{
var a = item;
}
bool boController = context.ApiDescription.ControllerAttributes().Any(e => e.GetType().Name == typeof(AuthorizeAttribute).Name);
bool boAction = context.ApiDescription.ActionAttributes().Any(e => e.GetType().Name == typeof(AuthorizeAttribute).Name);
//MemberAuthorizeAttribute 自定义的身份验证特性标记
var isAuthor = operation != null && context != null && (boController || boAction);
var isAllow = context.ApiDescription.ActionAttributes().Any(e => e.GetType().Name == typeof(AllowAnonymousAttribute).Name);
if (isAuthor && !isAllow)
{
//in query header
operation.Parameters.Add(new NonBodyParameter()
{
Name = "Authorization",
In = "header", //query formData ..
Description = "Token",
Required = false,
Type = "string"
});
}
}
}
5:修改项目属性:
6:启用
7:找到项目下:launchSettings.json 文件修改相关配置:
8:结果: