1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- // <author></author>
- // <date></date>
- // <description></description>
- 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<string>() };
- // 设置 Swagger UI 的标题和版本 (描述,联系人,许可证)
- options.SwaggerDoc("v1", new OpenApiInfo { Title = "ERP", Version = "v1" });
- // 安全方案
- options.AddSecurityDefinition(AuthConstant.HEADER, openApiSecurityScheme);
- // 请求头
- options.AddSecurityRequirement(securityRequirement);
- // 自定义逻辑
- options.OperationFilter<SwaggerDescriptionFilter>();
- options.OperationFilter<SwaggerSummaryFilter>();
- });
- }
- 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;
- }
- }
- }
- }
- }
|