UIStandardWebApi/UIStandardWebApi.WebCore/SwaggerExtend/SwaggerExtensions.cs
2025-04-08 08:41:01 +08:00

93 lines
3.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UIStandardWebApi.WebCore.SwaggerExtend
{
public static class SwaggerExtensions
{
/// <summary>
/// 配置Swagger的配置
/// </summary>
/// <param name="service"></param>
/// <param name="docName"></param>
/// <param name="docDescription"></param>
public static void AddSwaggerExt(this IServiceCollection service, string docName, string docDescription)
{
service.AddEndpointsApiExplorer();
service.AddSwaggerGen(option =>
{
foreach (var version in typeof(ApiVersions).GetEnumNames())
{
option.SwaggerDoc(version, new OpenApiInfo()
{
Title = !string.IsNullOrWhiteSpace(docName) ? docName : $"Api文档",
Version = version,
Description = !string.IsNullOrWhiteSpace(docDescription) ? docDescription : $"Api版本v1"
});
}
//option.OperationFilter<SwaggerFileUploadFcilter>();
// xml文档绝对路径
var file = Path.Combine(AppContext.BaseDirectory, $"{AppDomain.CurrentDomain.FriendlyName}.xml");
// true : 显示控制器层注释
option.IncludeXmlComments(file, true);
// 对action的名称进行排序如果有多个就可以看见效果了。
option.OrderActionsBy(o => o.RelativePath);
//#region 支持jwt token授权
//{
// //添加安全定义--配置支持token授权机制
// option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
// {
// Description = "请输入token,格式为 Bearer xxxxxxxx注意中间必须有空格",
// Name = "Authorization",
// In = ParameterLocation.Header,
// Type = SecuritySchemeType.ApiKey,
// BearerFormat = "JWT",
// Scheme = "Bearer"
// });
// //添加安全要求
// option.AddSecurityRequirement(new OpenApiSecurityRequirement
// {
// {
// new OpenApiSecurityScheme
// {
// Reference =new OpenApiReference()
// {
// Type = ReferenceType.SecurityScheme,
// Id ="Bearer"
// }
// },
// new string[]{ }
// }
// });
//}
//#endregion
});
}
/// <summary>
/// 使用Swagger中间件
/// </summary>
/// <param name="app"></param>
public static void UseSwaggerExt(this WebApplication app, string docName)
{
app.UseSwagger();
app.UseSwaggerUI(option =>
{
foreach (string version in typeof(ApiVersions).GetEnumNames())
{
option.SwaggerEndpoint($"/swagger/{version}/swagger.json", string.IsNullOrWhiteSpace(docName) ? docName : $"软件标准化Api文档【{version}】版本");
}
});
}
}
}