z8018
3 天以前 d8dc91f9c1fece5711e38edd1b1274cb9e579015
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 
using Microsoft.AspNetCore.Builder;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Helper;
 
namespace WIDESEA_Core.Middlewares
{
    /// <summary>
    /// Swagger中间件
    /// </summary>
    public static class SwaggerMiddleware
    {
        /// <summary>
        /// 配置应用程序使用Swagger中间件
        /// </summary>
        /// <param name="app">应用程序构建器</param>
        /// <param name="streamHtml">用于获取自定义Swagger首页HTML流的函数</param>
        /// <remarks>
        /// 此扩展方法配置Swagger UI,包括:
        /// 1. 设置API文档端点
        /// 2. 自定义文档标题和样式
        /// 3. 配置自定义首页流
        /// 4. 设置文档展开行为和路由前缀
        /// 如果streamHtml返回null,将抛出异常提示需要将index.html设置为嵌入资源
        /// </remarks>
        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.Get(new string[] { "ApiName" });
                c.SwaggerEndpoint($"/swagger/v1/swagger.json", $"{apiName} v1");
                
                // 将swagger首页,设置成我们自定义的页面,记得这个字符串的写法:{项目名.index.html}
                if (streamHtml.Invoke() == null)
                {
                    var msg = "index.html的属性,必须设置为嵌入的资源";
                    //Log.Error(msg);
                    throw new Exception(msg);
                }
                c.DocumentTitle = $"{apiName} 在线调试文档";
 
                c.InjectStylesheet("/css/swaggerdoc.css");
                c.InjectJavascript("/js/swaggerdoc.js");
                c.IndexStream = streamHtml;
                c.DocExpansion(DocExpansion.None); //->修改界面打开时自动折叠
 
                // 路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉,如果你想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = "doc";
                c.RoutePrefix = "";
            });
        }
    }
}