NetCore 配置Swagger

1.添加Nuget

install-package Swashbuckle.AspNetCore -project XXX -version 6.4.0

2.添加静态类扩展方法

2.1.生成项目xml:选中项目 / 右键 / 属性 / 生成 / 输出 / 选中xml文档文件

2.2.system_v1:必须唯一不重复,且【options.SwaggerDoc("system_v1"】必须与【options.SwaggerEndpoint("/swagger/system_v1/】一致,不然会异常【Failed to load API definition; Fetch error: response status is 404 /swagger/system_v1/swagger.json

 1     /// <summary>
 2     /// Swagger 静态类
 3     /// </summary>
 4     public static class SwaggerExtend
 5     {
 6         /// <summary>
 7         /// 添加服务: swagger
 8         /// </summary>
 9         /// <param name="services"></param>
10         /// <returns></returns>
11         public static void AddCustSwagger(this IServiceCollection services)
12         {
13             var version = "V1.0";
14             var apiName = "XXX系统";
15             services.AddSwaggerGen(options =>
16             {
17                 options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
18            
19                 options.SwaggerDoc("system_v1", new OpenApiInfo
20                 {
21                     Version = version,
22                     Title = $"{apiName} API",
23                     Description = $"{apiName} {version} 接口服务"
24                 });
25 
26                 //  获取应用程序所在目录
27                 var basePath = Path.GetDirectoryName(typeof(SwaggerExtend).Assembly.Location);
28                 var xmlPath = Path.Combine(basePath, "ProjectName.xml");
29                 //  swagger界面默认只显示 方法&字段 注释,不显示 控制器注释
30                 //  第二个参数为true, 则是controller的注释
31                 //options.IncludeXmlComments(xmlPath);
32                 options.IncludeXmlComments(xmlPath, true);
33             });
34         }
35 
36         /// <summary>
37         /// 添加中间件: swagger
38         /// </summary>
39         /// <param name="app"></param>
40         public static void UseCustSwagger(this IApplicationBuilder app)
41         {
42             app.UseSwagger();
43             app.UseSwaggerUI(options =>
44             {
45                 options.SwaggerEndpoint("/swagger/system_v1/swagger.json", "系统API");
46                 //  默认路径为:/swagger/index.html
47                 //  路由前缀 - 设置为空,可直接跳转到swagger页面:/index.html
48                 //  api测试可设置为空,部署时容易与前端路由冲突
49                 options.RoutePrefix = string.Empty;
50             });
51         } 
52     }

3.StartUp注册服务,添加中间件

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCustSwagger();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCustSwagger();
        }

 

posted @ 2022-09-21 15:56  Robot-Blog  阅读(84)  评论(0编辑  收藏  举报