zl程序教程

您现在的位置是:首页 >  后端

当前栏目

ASP.NET Core WebApi使用Swagger生成API说明文档【xml注释版】

2023-09-11 14:18:14 时间

⒈新建ASP.NET Core WebAPi项目

⒉添加 NuGet 包

Install-Package Swashbuckle.AspNetCore

⒊Startup中配置

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.AspNetCore.Mvc;
 8 using Microsoft.Extensions.Configuration;
 9 using Microsoft.Extensions.DependencyInjection;
10 using Microsoft.Extensions.Logging;
11 using Microsoft.Extensions.Options;
12 using Swashbuckle.AspNetCore.Swagger;
13 
14 namespace SwaggerXmlDemo
15 {
16     public class Startup
17     {
18         public Startup(IConfiguration configuration)
19         {
20             Configuration = configuration;
21         }
22 
23         public IConfiguration Configuration { get; }
24 
25         // This method gets called by the runtime. Use this method to add services to the container.
26         public void ConfigureServices(IServiceCollection services)
27         {
28             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
29 
30             //注册Swagger生成器,定义一个和多个Swagger 文档
31             services.AddSwaggerGen(option =>
32             {
33                 //配置第一个Doc
34                 option.SwaggerDoc("v1", new Info
35                 {
36                     Version = "v1",
37                     Title = "My API_1",
38                     Description = "Document Api",
39                     Contact = new Contact
40                     {
41                         Name = "fanqi",
42                         Email = "fanqisoft@163.com",
43                         Url = "https://www.coreqi.cn"                   
44                     }
45                 });
46             });
47         }
48 
49         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
50         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
51         {
52             if (env.IsDevelopment())
53             {
54                 app.UseDeveloperExceptionPage();
55             }
56 
57             //启用中间件服务生成Swagger作为JSON终结点
58             app.UseSwagger();
59 
60             //启用中间件服务对swagger-ui,指定Swagger JSON终结点
61             app.UseSwaggerUI(c =>
62             {
63                 c.SwaggerEndpoint("/swagger/v1/swagger.json", "DemoAPI V1");
64                 //c.RoutePrefix = "swagger";  //默认
65                 c.RoutePrefix = string.Empty;
66             });
67 
68             app.UseMvc();
69         }
70     }
71 }

⒋添加注释信息

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 
 6 namespace SwaggerXmlDemo.Models
 7 {
 8     /// <summary>
 9     /// 用户实体类
10     /// </summary>
11     public class User
12     {
13         /// <summary>
14         /// 用户主键Id
15         /// </summary>
16         /// <example>1</example>
17         public int id { get; set; }
18         /// <summary>
19         /// 用户名
20         /// </summary>
21         /// <example>fanqi</example>
22         public string username { get; set; }
23         /// <summary>
24         /// 用户密码
25         /// </summary>
26         /// <example>admin</example>
27         public string password { get; set; }
28         /// <summary>
29         /// 用户年龄
30         /// </summary>
31         /// <example>25</example>
32         public int? age { get; set; }
33         /// <summary>
34         /// 用户邮箱
35         /// </summary>
36         /// <example>fanqisoft@163.com</example>
37         public string email { get; set; }
38     }
39 }

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Http;
 6 using Microsoft.AspNetCore.Mvc;
 7 using SwaggerXmlDemo.Models;
 8 
 9 namespace SwaggerDemo.Controllers
10 {
11     /// <summary>
12     /// 用户Api控制器
13     /// </summary>
14     [Route("api/[controller]")]
15     [ApiController]
16     public class UserController : ControllerBase
17     {
18         /// <summary>
19         /// 获取系统用户列表
20         /// </summary>
21         /// <remarks>
22         /// Demo
23         /// Get /api/user/get
24         /// </remarks>
25         /// <returns>系统用户列表</returns>
26         /// <response code="201">返回用户列表</response>
27         /// <response code="401">没有权限</response>
28         [HttpGet("get")]
29         [ProducesResponseType(201)]
30         [ProducesResponseType(401)]
31         public IList<User> GetUsers()
32         {
33             return new List<User>
34             {
35                 new User{ id = 1,username = "fanqi",password = "admin",age = 25,email = "fanqisoft@163.com"},
36                 new User{ id = 2,username = "gaoxing",password = "admin",age = 22,email = "gaoxing@163.com"}
37             };
38         }
39 
40         /// <summary>
41         /// 新建用户
42         /// </summary>
43         /// <param name="user">新建用户信息</param>
44         /// <returns>是否创建成功信息</returns>
45         [HttpPost("add")]
46         public IActionResult CreateUser([FromForm] User user)
47         {
48             return Ok();
49         }
50     }
51 }

 

 

⒋启用XML注释

  1.右键单击“解决方案资源管理器”中的项目,然后选择“属性”

  2.勾选“生成”选项卡“输出”部分的“XML 文档文件”框

右键生成的XML文件,选择属性。修改“复制到输出目录”为“始终复制”。

启用 XML 注释后会为未记录的公共类型和成员提供调试信息将会出现很多CS1591警告信息。直接无视即可。

警告   CS1591	缺少对公共可见类型或成员“xxxxx”的 XML 注释 指定了 /doc 编译器选项,但是一个或多个构造没有注释。

如果有强迫症,可以按照下图所示进行取消

注意上面生成的xml文档文件的路径,

 注意:

​ 1.对于 Linux 或非 Windows 操作系统,文件名和路径区分大小写。 例如,“SwaggerDemo.xml”文件在 Windows 上有效,但在 CentOS 上无效。

​ 2.获取应用程序路径,建议采用Path.GetDirectoryName(typeof(Program).Assembly.Location)这种方式或者·AppContext.BaseDirectory这样来获取

⒌为 Swagger JSON和UI设置xml文档注释路径

 

 1         // This method gets called by the runtime. Use this method to add services to the container.
 2         public void ConfigureServices(IServiceCollection services)
 3         {
 4             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
 5 
 6             //注册Swagger生成器,定义一个和多个Swagger 文档
 7             services.AddSwaggerGen(option =>
 8             {
 9                 //配置第一个Doc
10                 option.SwaggerDoc("v1", new Info
11                 {
12                     Version = "v1",
13                     Title = "My API_1",
14                     Description = "Document Api",
15                     Contact = new Contact
16                     {
17                         Name = "fanqi",
18                         Email = "fanqisoft@163.com",
19                         Url = "https://www.coreqi.cn"                   
20                     }
21                 });
22 
23                 // 为 Swagger JSON and UI设置xml文档注释路径
24                 //var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
25                 //var xmlPath = Path.Combine(basePath, "SwaggerXmlDemo.xml");
26                 var filePath = Path.Combine(System.AppContext.BaseDirectory, "SwaggerXmlDemo.xml");
27                 option.IncludeXmlComments(filePath);
28             });
29         }

 

⒍查看效果