Files
Api/DouyinApi.Extensions/Middlewares/SwaggerMiddleware.cs
2025-11-04 21:09:16 +08:00

54 lines
2.2 KiB
C#
Raw Permalink 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 DouyinApi.Common;
using Microsoft.AspNetCore.Builder;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.IO;
using System.Linq;
using Serilog;
using static DouyinApi.Extensions.CustomApiVersion;
namespace DouyinApi.Extensions.Middlewares
{
/// <summary>
/// Swagger中间件
/// </summary>
public static class SwaggerMiddleware
{
public static void UseSwaggerMiddle(this IApplicationBuilder app, Func<Stream> streamHtml)
{
if (app == null) throw new ArgumentNullException(nameof(app));
app.UseSwagger();
app.UseSwaggerUI(c =>
{
//根据版本名称倒序 遍历展示
var apiName = AppSettings.app(new string[] { "Startup", "ApiName" });
typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version => { c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{apiName} {version}"); });
c.SwaggerEndpoint($"https://petstore.swagger.io/v2/swagger.json", $"{apiName} pet");
// 将swagger首页设置成我们自定义的页面记得这个字符串的写法{项目名.index.html}
if (streamHtml.Invoke() == null)
{
var msg = "index.html的属性必须设置为嵌入的资源";
Log.Error(msg);
throw new Exception(msg);
}
c.IndexStream = streamHtml;
c.DocExpansion(DocExpansion.None); //->修改界面打开时自动折叠
if (Permissions.IsUseIds4)
{
c.OAuthClientId("blogadminjs");
}
//增加令牌本地缓存 reload不会丢失
c.ConfigObject.AdditionalItems.Add("persistAuthorization","true");
// 路径配置设置为空表示直接在根域名localhost:8001访问该文件,注意localhost:8001/swagger是访问不到的去launchSettings.json把launchUrl去掉如果你想换一个路径直接写名字即可比如直接写c.RoutePrefix = "doc";
c.RoutePrefix = "";
});
}
}
}