You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
3.4 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
namespace DS.Module.Swagger
{
/// <summary>
/// swagger服务扩展
/// </summary>
public static class SwaggerServiceExtensions
{
public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// 设置XML文档路径
//var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
//c.IncludeXmlComments(xmlPath);
foreach (var xml in Directory.GetFiles(AppContext.BaseDirectory, "*.xml"))
{
c.IncludeXmlComments(xml);
}
c.CustomOperationIds(api =>
{
return api.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null;
});
// 一定要返回true
c.DocInclusionPredicate((docName, description) => { return true; });
// 开启加权小锁
c.OperationFilter<AddResponseHeadersFilter>();
c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
// 在header中添加token传递到后台
c.OperationFilter<SecurityRequirementsOperationFilter>();
// 必须是 Bearer
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
Name = "Authorization", //jwt默认的参数名称
In = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey,
// BearerFormat = "JWT", //标识承载令牌的格式 该信息主要是出于文档目的
Scheme = "Bearer " //授权中要使用的HTTP授权方案的名称
});
//在Heder中添加Token 传递到后台
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
}
},
new string[] { "readAccess", "writeAccess" }
}
});
});
return services;
}
public static WebApplication UseSwaggerDocumentation(this WebApplication app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
c.RoutePrefix = "swagger"; // 设置Swagger UI为应用的根
});
return app;
}
}
}