//
//
//
using ERP.Framework.Constants;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace ERP.Framework.Extensions
{
public static class SwaggerExtension
{
public static void AddSwagger(this IServiceCollection services)
{
services.AddSwaggerGen(options =>
{
var openApiSecurityScheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = AuthConstant.HEADER
},
Scheme = "oauth2",
Name = AuthConstant.HEADER,
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
};
var securityRequirement = new OpenApiSecurityRequirement { [openApiSecurityScheme] = new List() };
// 设置 Swagger UI 的标题和版本 (描述,联系人,许可证)
options.SwaggerDoc("v1", new OpenApiInfo { Title = "ERP", Version = "v1" });
// 安全方案
options.AddSecurityDefinition(AuthConstant.HEADER, openApiSecurityScheme);
// 请求头
options.AddSecurityRequirement(securityRequirement);
// 自定义逻辑
options.OperationFilter();
options.OperationFilter();
});
}
private class PrefixDocumentFilter : IDocumentFilter
{
private readonly string _prefix;
public PrefixDocumentFilter(string prefix)
{
_prefix = prefix;
}
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var paths = new OpenApiPaths();
foreach (var path in swaggerDoc.Paths)
{
paths.Add(_prefix + path.Key, path.Value);
}
swaggerDoc.Paths = paths;
}
}
private class SwaggerDescriptionFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var attribute = context.MethodInfo
.GetCustomAttributes(typeof(SwaggerOperationAttribute), false)
.FirstOrDefault() as SwaggerOperationAttribute;
if (attribute != null && !string.IsNullOrEmpty(attribute.Description))
{
operation.Description = attribute.Description;
}
}
}
public class SwaggerSummaryFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var attribute = context.MethodInfo
.GetCustomAttributes(typeof(SwaggerOperationAttribute), false)
.FirstOrDefault() as SwaggerOperationAttribute;
if (attribute != null && !string.IsNullOrEmpty(attribute.Summary))
{
operation.Summary = attribute.Summary;
}
}
}
}
}