cs
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.IO;
using static System.Net.WebRequestMethods;
public class RemoveServiceSuffixOperationFilter : IOperationFilter
{
/// <summary>
/// 修改路由名称的过滤器 去除掉后缀的Service
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Tags.Count > 0)
{
foreach (var tag in operation.Tags)
{
tag.Name = tag.Name.Replace("Service", "");
}
}
}
}
/// <summary>
/// OpenApi过滤器
/// </summary>
public class TagReorderDocumentFilter : IDocumentFilter
{
/// <summary>
/// 修改路由名称的过滤器 去除掉后缀的Service
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
//修改模块名称
foreach (var tag in swaggerDoc.Tags)
{
tag.Name = tag.Name.Replace("Service", "");
}
//修改路由中的模块
foreach (var path in swaggerDoc.Paths)
{
foreach (var o in path.Value.Operations)
{
foreach (var tag in o.Value.Tags)
{
tag.Name = tag.Name.Replace("Service", "");
}
}
}
//swaggerDoc.Tags.Clear(); //清空Tags
防止重复
//Dictionary<string, OpenApiTag> dic = new Dictionary<string, OpenApiTag>();
重新添加Tags
//foreach (var path in swaggerDoc.Paths)
//{
// foreach (var o in path.Value.Operations)
// {
// foreach (var tag in o.Value.Tags)
// {
// if (!dic.Keys.Contains(tag.Name))
// {
// dic.Add(tag.Name, tag);
// swaggerDoc.Tags.Add(tag);
// }
// }
// }
//}
}
}
在program.cs中注册
cs
//添加Swagger的Authiozer的按钮鉴权
builder.Services.AddSwaggerGen(s =>
{
s.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
string netXmlString = AppContext.BaseDirectory + "/WebApiBasics.Net.xml";
s.IncludeXmlComments(netXmlString, true);
string entityXmlStringa = AppDomain.CurrentDomain.BaseDirectory + "/WebApiBasics.Entity.xml";
s.IncludeXmlComments(entityXmlStringa, true);
string coreXmlStringa = AppDomain.CurrentDomain.BaseDirectory + "/WebApiBasics.Core.xml";
s.IncludeXmlComments(coreXmlStringa, true);
// 添加修改路由名称的过滤器 去除掉后缀的Service
s.OperationFilter<RemoveServiceSuffixOperationFilter>();
s.DocumentFilter<TagReorderDocumentFilter>();
s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
s.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"}
},new string[] { }
}
});
});
效果