Files
8357WMS/HHWMS.Web/Support/SwaggerExtension.cs
T
2023-07-25 19:20:18 +08:00

55 lines
2.0 KiB
C#

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace HHWMS.Web.Support
{
public static class SwaggerExtension
{
public static void AddSwaggerGenExt(this WebApplicationBuilder builder)
{
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(
option =>
{
option.SwaggerDoc("Sys", new OpenApiInfo { Title = "系统", Version = "v1" });
option.SwaggerDoc("User", new OpenApiInfo { Title = "自定义", Version = "v1" });
option.DocInclusionPredicate((docName, apiDesc) =>
{
if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo))
return false;
var versions = methodInfo.DeclaringType
.GetCustomAttributes(true)
.OfType<ApiExplorerSettingsAttribute>()
.Select(x => x.GroupName);
if (docName.ToLower() == "sys" && versions.FirstOrDefault() == null)
return true; // 不写ApiExplorerSetting默认显示在Sys组
return versions.Any(x => x.ToString() == docName);
});
var xml = Path.Combine(AppContext.BaseDirectory, "HHWMS.Web.xml");
option.IncludeXmlComments(xml, true);
}
);
}
public static void UseSwaggerExt(this WebApplication app)
{
app.UseSwagger();
app.UseSwaggerUI(option =>
{
option.SwaggerEndpoint("/swagger/User/swagger.json", "自定义");
option.SwaggerEndpoint("/swagger/Sys/swagger.json", "系统接口");
});
}
}
}