1:提早添加:程序集 Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530ajson
2:在 Startup 的 ConfigureServices中添加以下:app
//註冊Swagger生成器,定義一個和多個Swagger 文檔
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Title = $"ERP接口",
Version = "v1",
ui
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>(); //Token3d
});orm
3:在Configure下添加使用:xml
//啓用中間件服務生成Swagger做爲JSON終結點
app.UseSwagger();
//啓用中間件服務對swagger-ui,指定Swagger JSON終結點
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});中間件
4:處理受權:blog
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;
}ip
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:結果: