ASP.NET Core WebApi使用Swagger生成API說明文檔【xml注釋版】


⒈新建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         }

 

⒍查看效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM