對於開發人員來說,構建一個消費應用程序時去了解各種各樣的 API 是一個巨大的挑戰。
在你的 Web API 項目中使用 Swagger 的 .NET Core 封裝 Swashbuckle 可以幫助你創建良好的文檔和幫助頁面。 Swashbuckle 可以通過修改 Startup.cs 作為一組 NuGet 包方便的加入項目。
Swashbuckle 是一個開源項目,為使用 ASP.NET Core MVC 構建的 Web APIs 生成 Swagger 文檔。
Swagger 是一個機器可讀的 RESTful API 表現層,它可以支持交互式文檔、客戶端 SDK 的生成和可被發現。
Swashbuckle 有兩個核心的組件
Swashbuckle.SwaggerGen : 提供生成描述對象、方法、返回類型等的 JSON Swagger 文檔的功能。
Swashbuckle.SwaggerUI : 是一個嵌入式版本的 Swagger UI 工具,使用 Swagger UI 強大的富文本表現形式來可定制化的來描述 Web API 的功能,並且包含內置的公共方法測試工具。
新建一個ASP.NET Core WebApi 項目,項目結構如下圖所示:
使用NUget進行添加Swashbuckle
1、工具->NUget包管理器->程序包管理器控制台
2、在控制台輸入: Install-Package Swashbuckle -Pre 按下回車鍵
3、安裝Swashbuckle完成:
4、安裝Swashbuckle完成后台項目的引用發生了變化:
5、在 project.json 中添加多了一項配置 "Swashbuckle": "6.0.0-beta902" :
7、啟用 XML 注釋, 在 Visual Studio 中右擊項目並且選擇 Properties 在 Output Settings 區域下面點擊 XML Documentation file 。
9、在 project.json 中設置 “xmlDoc”: true 來啟用 XML 注釋。
10、在Startup.cs類的 ConfigureServices 方法中,允許中間件提供和服務生成 JSON 文檔以及 SwaggerUI。Configure 方法中把 SwaggerGen 添加到 services 集合。配置 Swagger 使用生成的 XML 文件
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.Extensions.Configuration; 8 using Microsoft.Extensions.DependencyInjection; 9 using Microsoft.Extensions.Logging; 10 using Microsoft.Extensions.PlatformAbstractions; 11 using Swashbuckle.Swagger.Model; 12 13 namespace dotNetCore_Test1 14 { 15 16 public class Startup 17 { 18 public Startup(IHostingEnvironment env) 19 { 20 var builder = new ConfigurationBuilder() 21 .SetBasePath(env.ContentRootPath) 22 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 23 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); 24 25 if (env.IsEnvironment("Development")) 26 { 27 // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. 28 builder.AddApplicationInsightsSettings(developerMode: true); 29 } 30 builder.AddEnvironmentVariables(); 31 Configuration = builder.Build(); 32 } 33 34 public IConfigurationRoot Configuration { get; } 35 36 // This method gets called by the runtime. Use this method to add services to the container 37 public void ConfigureServices(IServiceCollection services) 38 { 39 // Add framework services. 40 services.AddApplicationInsightsTelemetry(Configuration); 41 42 services.AddMvc(); 43 44 //services.AddLogging(); 45 46 // 注入的實現ISwaggerProvider使用默認設置 47 services.AddSwaggerGen(); 48 49 services.ConfigureSwaggerGen(options => 50 { 51 options.SingleApiVersion(new Info 52 { 53 Version = "v1", 54 Title = "測試ASP.NET Core WebAPI生成文檔(文檔說明)", 55 Description = "A simple example ASP.NET Core Web API", 56 TermsOfService = "None", 57 Contact = new Contact { Name = "linyongjie", Email = "", Url = "https://docs.microsoft.com/zh-cn/aspnet/core/" }, 58 License = new License { Name = "Swagger官網", Url = "http://swagger.io/" } 59 }); 60 61 var basePath = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath; // 獲取到應用程序的根路徑 62 options.IncludeXmlComments(basePath + "\\dotNetCore_Test1.xml"); //是需要設置 XML 注釋文件的完整路徑 63 }); 64 65 66 } 67 68 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline 69 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 70 { 71 loggerFactory.AddConsole(Configuration.GetSection("Logging")); 72 loggerFactory.AddDebug(); 73 74 app.UseApplicationInsightsRequestTelemetry(); 75 76 app.UseApplicationInsightsExceptionTelemetry(); 77 78 app.UseMvc(); 79 80 81 app.UseSwagger(); //使中間件服務生成Swagger作為JSON端點 82 83 app.UseSwaggerUi(); //使中間件服務swagger-ui assets (HTML、javascript、CSS等等) 84 85 } 86 } 87 }
11、新建一個User(用戶)Model用於測試:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel.DataAnnotations; 4 using System.Linq; 5 using System.Threading.Tasks; 6 7 namespace dotNetCore_Test1.Models 8 { 9 10 /// <summary> 11 /// 用戶模型 12 /// </summary> 13 public class User 14 { 15 16 17 /// <summary> 18 /// 年齡 19 /// </summary> 20 public int Age { set; get; } 21 22 /// <summary> 23 /// 名稱 24 /// </summary> 25 [Required] //此配置可以約束(Swagger )傳進來的參數值 不能為空 26 public string Name { get; set; } 27 28 29 /// <summary> 30 /// 性別 31 /// </summary> 32 public string Sex { get; set; } 33 } 34 }
12、添加了XML注釋控制器例子:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using Microsoft.AspNetCore.Mvc; 6 7 namespace dotNetCore_Test1.Controllers 8 { 9 /// <summary> 10 /// 測試 Swagger的 XML 注釋 11 /// </summary> 12 [Route("api/[controller]")] 13 public class ValuesController : Controller 14 { 15 /// <summary> 16 /// 獲得一個數組信息 17 /// </summary> 18 /// <returns></returns> 19 [HttpGet] 20 public IEnumerable<string> Get() 21 { 22 return new string[] { "value1", "value2" }; 23 } 24 25 /// <summary> 26 /// 根據id獲取信息 27 /// </summary> 28 /// <param name="id">主鍵唯一標識</param> 29 /// <returns>返回一個值</returns> 30 [HttpGet("{id}")] 31 public string Get(int id) 32 { 33 return "value"; 34 } 35 36 /// <summary> 37 /// 添加一個用戶 38 /// </summary> 39 /// <remarks> 40 /// 41 /// POST /User 42 /// { 43 /// "Age": "年齡", 44 /// "Name": "名稱", 45 /// "Sex": "性別 46 /// } 47 /// 48 /// </remarks> 49 /// <param name="item">用戶的json對象</param> 50 /// <returns>返回一個對象</returns> 51 /// <response code="201">返回新創建的項目</response> 52 /// <response code="400">如果item是null</response> 53 [HttpPost] 54 [ProducesResponseType(typeof(dotNetCore_Test1.Models.User), 201)] 55 [ProducesResponseType(typeof(dotNetCore_Test1.Models.User), 400)] 56 [HttpPost] 57 public IActionResult Post([FromBody]dotNetCore_Test1.Models.User item) 58 { 59 if (item == null) 60 { 61 return BadRequest(); 62 } 63 return Ok(item); 64 } 65 66 67 68 69 /// <summary> 70 /// 刪除一個對象 71 /// </summary> 72 /// <remarks> 73 /// 這里可以寫詳細的備注 74 /// </remarks> 75 /// <param name="id">主鍵id標識</param> 76 [HttpDelete("{id}")] 77 public void Delete(int id) 78 { 79 } 80 } 81 }
13、通過訪問 http://localhost:<random_port>/swagger/ui
查看Swagger 自動生成文檔 (<random_port> 表示IIS Express隨機分配的端口號,我測試的demo分配的端口號是:51109,所以我這里查看Swagger生成的文檔地址是http://localhost:51109/swagger/ui/index.html#/Values
)生成的文檔如下圖:
13.1、
13.2
13.3
13.4
配置 Swagger 使用生成的 XML 文件