Doraemon

小叮当    2012 - 2023
Doraemon

Choose mode

  • dark
  • auto
  • light
首页
Category
  • 前端开发
  • 后端
  • 数据库
  • 运维
Tag
TimeLine
关于
  • 关于我
Contact
  • GitHub
author-avatar

小叮当

39

Article

25

Tag

首页
Category
  • 前端开发
  • 后端
  • 数据库
  • 运维
Tag
TimeLine
关于
  • 关于我
Contact
  • GitHub

使用VS Code开发.NET Core 0008 - 添加Swagger

小叮当    2012 - 2023

使用VS Code开发.NET Core 0008 - 添加Swagger


小叮当 2020-11-21 .Net Core后端Dot-net-with-vs-code

首先在 Extensions 中添加 Nugget 包Swashbuckle.AspNetCore.Filters,Swashbuckle.AspNetCore

    <PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="6.0.1" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
1
2

# 一、在 Extensions 中创建SwaggerMiddle.cs

    /// <summary>
    /// Swagger中间件
    /// </summary>
    public static class SwaggerMiddle
    {
        //TODO:
        // private static readonly ILog log = LogManager.GetLogger(typeof(SwaggerMiddle));

        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 = "测试api";
                // 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;

                // if (Permissions.IsUseIds4)
                // {
                //     c.OAuthClientId("");
                // }


                // 路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉,如果你想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = "doc";
                c.RoutePrefix = "";
                c.DefaultModelsExpandDepth(-1);

            });
        }

    }

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

# 二、在 Extensions 中创建SwaggerSetup.cs

    /// <summary>
    ///  Swagger 启动服务
    /// </summary>
    public static class SwaggerSetup
    {
        //TODO:
        // private static readonly ILog log =
        // LogManager.GetLogger(typeof(SwaggerSetup));

        public static void AddSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            var basePath = AppContext.BaseDirectory;
            //var basePath2 = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
            var ApiName = "开发环境API";

            //TODO:
            // var ApiName = AppsettingsHelper.app(new string[] { "Startup", "ApiName" });

            services.AddSwaggerGen(c =>
            {
                //遍历出全部的版本,做文档信息展示
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title = $"{ApiName} 接口文档——{RuntimeInformation.FrameworkDescription}",
                        Description = $"{ApiName} HTTP API " + version,
                        Contact = new OpenApiContact { Name = ApiName, Email = "", Url = new Uri("https://test.com") },
                        License = new OpenApiLicense { Name = ApiName + " 官方文档", Url = new Uri("http://test.com/doc") }
                    });
                    c.OrderActionsBy(o => o.RelativePath);
                });


                try
                {
                    //这个就是刚刚配置的xml文件名
                    var xmlPath = Path.Combine(basePath, "Sec.Mon.Api.xml");
                    //默认的第二个参数是false,这个是controller的注释,记得修改
                    c.IncludeXmlComments(xmlPath, true);

                    //这个就是Model层的xml文件名
                    var xmlModelPath = Path.Combine(basePath, "Sec.Mon.Model.xml");
                    c.IncludeXmlComments(xmlModelPath);
                }
                catch (Exception ex)
                {
                    //TODO:
                    // log.Error("Api.xml和Model.xml 丢失,请检查并拷贝。\n" + ex.Message);
                }

                // 开启加权小锁
                c.OperationFilter<AddResponseHeadersFilter>();
                c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token,传递到后台
                c.OperationFilter<SecurityRequirementsOperationFilter>();


                // Jwt Bearer 认证,必须是 oauth2
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });

            });
        }
    }


    /// <summary>
    /// 自定义版本
    /// </summary>
    public class CustomApiVersion
    {
        /// <summary>
        /// Api接口版本 自定义
        /// </summary>
        public enum ApiVersions
        {
            /// <summary>
            /// V1 版本
            /// </summary>
            V1 = 1,
            /// <summary>
            /// V2 版本
            /// </summary>
            V2 = 2,
        }
    }
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

# 三、在 Startup 中引用

//添加拓展services
services.AddSwaggerSetup();//启动swagger
1
2
// 封装Swagger展示
app.UseSwaggerMiddle(() => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Sec.Mon.Api.index.html"));
1
2

# 四、修改项目文件.csproj,输出 xml

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>..\Sec.Mon.Api\Sec.Mon.Api.xml</DocumentationFile>
    <NoWarn>1701;1702;1591</NoWarn>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DocumentationFile>..\Sec.Mon.Api\Sec.Mon.Api.xml</DocumentationFile>
    <NoWarn>1701;1702;1591</NoWarn>
  </PropertyGroup>
1
2
3
4
5
6
7
8
9
  • 一、在 Extensions 中创建SwaggerMiddle.cs
  • 二、在 Extensions 中创建SwaggerSetup.cs
  • 三、在 Startup 中引用
  • 四、修改项目文件.csproj,输出 xml