認識Swagger
Swagger 是一個規范和完整的框架,用于生成、描述、呼叫和可視化 RESTful 風格的 Web 服務,總體目標是使客戶端和檔案系統作為服務器以同樣的速度來更新,檔案的方法,引數和模型緊密集成到服務器端的代碼,允許API來始終保持同步,
作用:
- 介面的檔案在線自動生成,
- 功能測驗,
為什么使用Swagger作為REST APIs檔案生成工具
- Swagger 可以生成一個具有互動性的API控制臺,開發者可以用來快速學習和嘗試API,
- Swagger 可以生成客戶端SDK代碼用于各種不同的平臺上的實作,
- Swagger 檔案可以在許多不同的平臺上從代碼注釋中自動生成,
- Swagger 有一個強大的社區,里面有許多強悍的貢獻者,
安裝Nuget包搜索Swashbuckle.AspNetCore
因為是.NetCore3.0 ,所以一定要勾選包括預覽發行版,安裝最新預發行版 5.0.0-rc4,千萬不要安裝最新穩定版,穩定版會報錯,
穩定版報錯資訊:
1 Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: 2 Swashbuckle.AspNetCore.Swagger.ISwaggerProvider Lifetime: Transient ImplementationType: 3 Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator': Failed to compare two elements in the array.) 4 (Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory Lifetime: 5 Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryFactory': Failed to compare two elements in the array.)
解決辦法就是3.0版本中要安裝現在預覽發行版5.0.0-rc4
在.NetCore3.0中 配置Swagger 也發生變化,
由以前的
1 services.AddSwaggerGen(c => 2 { 3 c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); 4 });
變更為
1 services.AddSwaggerGen(c => 2 { 3 c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 4 });
其中最大的變化就是Info這里,在以前2.0版本中是由Swagger來管理的,在3.0版本中統一變更為 OpenApi管理,OpenApi 在官方檔案中介紹為是用于管理專案內 OpenAPI 參考的 .NET Core 全域工具,
參考地址:(https://docs.microsoft.com/zh-cn/aspnet/core/web-api/microsoft.dotnet-openapi?view=aspnetcore-3.1 "使用 OpenAPI 工具開發 ASP.NET Core 應用")
所以在添加完Swagger 包后,還要在專案中添加Microsoft.OpenApi包
注冊Swagger
1 public void ConfigureServices(IServiceCollection services) 2 { 3 4 services.AddControllers(); 5 6 services.AddSwaggerGen(c => 7 { 8 c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 9 }); 10 11 }
配置Swagger UI
1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 2 { 3 if (env.IsDevelopment()) 4 { 5 app.UseDeveloperExceptionPage(); 6 } 7 app.UseHttpsRedirection(); 8 app.UseRouting(); 9 app.UseAuthorization(); 10 //啟用Swagger 11 app.UseSwagger(); 12 //配置Swagger UI 13 app.UseSwaggerUI(c => 14 { 15 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API"); //注意中間段v1要和上面SwaggerDoc定義的名字保持一致 16 }); 17 app.UseEndpoints(endpoints => 18 { 19 endpoints.MapControllers(); 20 }); 21 }
啟動專案
CTRL+F5啟動專案,并導航到 http://localhost:port/swagger 通過Swagger UI游覽API檔案
Swagger的高級用法(自定義擴展)
在 AddSwaggerGen 方法的進行如下的配置操作會添加諸如作者、許可證和說明資訊等:
1 services.AddSwaggerGen(c => 2 { 3 c.SwaggerDoc("v1", new OpenApiInfo 4 { 5 Title = "My API", 6 Version = "v1", 7 Description = "API檔案描述", 8 Contact = new OpenApiContact 9 { 10 Email = "[email protected]", 11 Name = "開源NetCore", 12 Url = new Uri("http://www.netcore.pub/") 13 }, 14 License = new OpenApiLicense 15 { 16 Name = "許可證名稱", 17 Url = new Uri("http://www.netcore.pub/") 18 } 19 }); 20 });
Swagger UI 顯示版本的資訊如下圖所示
為API介面方法添加注釋
大家先點開API,展開如下圖所示,可是沒有注釋呀,怎么添加注釋呢?
按照下列代碼所示用三個/添加檔案注釋,如下所示
1 /// <summary> 2 /// 這是一個API注釋 3 /// </summary> 4 /// <returns></returns> 5 [HttpGet] 6 public IEnumerable<WeatherForecast> Get() 7 { 8 var rng = new Random(); 9 return Enumerable.Range(1, 5).Select(index => new WeatherForecast 10 { 11 Date = DateTime.Now.AddDays(index), 12 TemperatureC = rng.Next(-20, 55), 13 Summary = Summaries[rng.Next(Summaries.Length)] 14 }) 15 .ToArray(); 16 }
然后運行專案,回到Swagger UI中去查看注釋是否出現了呢
還是沒出現?一臉懵逼??? 別急往下看!
啟用XML注釋
可使用以下方法啟用 XML 注釋:
右鍵單擊“解決方案資源管理器”中的專案,然后選擇“屬性”
查看“生成”選項卡的“輸出”部分下的“XML 檔案檔案”框
啟用 XML 注釋后會為未記錄的公共型別和成員提供除錯資訊,如果出現很多警告資訊 例如,以下訊息指示違反警告代碼 1591:
1 warning CS1591: Missing XML comment for publicly visible type or member 'TodoController.GetAll()'
如果你有強迫癥,想取消警告怎么辦呢?可以按照下圖所示進行取消

注意上面生成的xml檔案檔案的路徑,
注意:
? 1.對于 Linux 或非 Windows 作業系統,檔案名和路徑區分大小寫, 例如,“Kylin.Wiki.xml”檔案在 Windows 上有效,但在 CentOS 上無效,
? 2.獲取應用程式路徑,建議采用Path.GetDirectoryName(typeof(Program).Assembly.Location)這種方式或者·AppContext.BaseDirectory這樣來獲取
1 services.AddSwaggerGen(c => 2 { 3 c.SwaggerDoc("v1", new OpenApiInfo 4 { 5 Title = "My API", 6 Version = "v1", 7 Description = "API檔案描述", 8 Contact = new OpenApiContact 9 { 10 Email = "[email protected]", 11 Name = "開源NetCore", 12 Url = new Uri("http://www.netcore.pub/") 13 }, 14 License = new OpenApiLicense 15 { 16 Name = "許可證名稱", 17 Url = new Uri("http://www.netcore.pub/") 18 } 19 }); 20 // 為 Swagger JSON and UI設定xml檔案注釋路徑 21 var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//獲取應用程式所在目錄(絕對,不受作業目錄影響,建議采用此方法獲取路徑) 22 var xmlPath = Path.Combine(basePath, "Kylin.Wiki.xml"); 23 c.IncludeXmlComments(xmlPath); 24 });
重新生成并運行專案查看一下注釋出現了沒有

通過上面的操作可以總結出,Swagger UI 顯示上述注釋代碼的元素的內部文本作為api大的注釋!
當然你還可以將 remarks 元素添加到 Get 操作方法檔案, 它可以補充元素中指定的資訊,并提供更可靠的 Swagger UI, 元素內容可包含文本、JSON 或 XML, 代碼如下:
1 /// <summary> 2 /// 這是一個帶引數的get請求 3 /// </summary> 4 /// <remarks> 5 /// 例子: 6 /// Get api/Values/1 7 /// </remarks> 8 /// <param name="id">主鍵</param> 9 /// <returns>測驗字串</returns> 10 public ActionResult<string> Get(int id) 11 { 12 return $"你請求的 id 是 {id}"; 13 }
重新生成下專案,當好到SwaggerUI看到如下所示:

描述回應型別
介面使用者最關心的就是介面的回傳內容和回應型別啦,下面展示一下201和400狀態碼的一個簡單例子:
我們需要在我們的方法上添加:
[ProducesResponseType(201)]
[ProducesResponseType(400)]
然后添加相應的狀態說明:回傳value字串如果id為空
最終代碼應該是這個樣子:
1 /// <summary> 2 /// 這是一個帶引數的get請求 3 /// </summary> 4 /// <remarks> 5 /// 例子: 6 /// Get api/Values/1 7 /// </remarks> 8 /// <param name="id">主鍵</param> 9 /// <returns>測驗字串</returns> 10 /// <response code="201">回傳value字串</response> 11 /// <response code="400">如果id為空</response> 12 // GET api/values/2 13 [HttpGet("{id}")] 14 [ProducesResponseType(201)] 15 [ProducesResponseType(400)] 16 public ActionResult<string> Get(int id) 17 { 18 return $"你請求的 id 是 {id}"; 19 }
效果如下所示
狀態相應效果
使用SwaggerUI測驗api介面
下面我們通過一個小例子通過SwaggerUI除錯下介面吧
點擊一個需要測驗的API介面,然后點擊Parameters左右邊的“Try it out ” 按鈕
在出現的引數文本框中輸入引數,如下圖所示的,輸入引數2
點擊執行按鈕,會出現下面所示的格式化后的Response,如下圖所示
好了,今天的在ASP.NET Core WebApi 3.0 中使用Swagger生成api說明檔案教程就到這里了,希望能夠對大家學習在ASP.NET Core中使用Swagger生成api檔案有所幫助!
「開源NetCore,如果覺得我的文章對您有用,請幫助本站成長」
除非注明,文章均由開源 NetCore 整理發布,歡迎轉載,
轉載請注明本文地址:http://www.netcore.pub/167.html
站長會將優質文章在各大平臺同步更新、推送,歡迎大家訪問、訂閱:
博客園: https://www.cnblogs.com/Zenderblogs/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/83039.html
標籤:.NET Core
