.Net 6 Open API a.k.a Swagger

Joe Chiu
appxtech

--

.net 6 預設的 webapi 專案範本,已經幫我們預設啟用了 swagger 服務,在 .net 6 使用 swagger 整合度很高也非常好上手,Swagger 能產生完整文檔和提供 API 測試,還可以方便的透過 CLI 工具來產生 client 端 code 以強型別來對接 API,功能非常強大。

Nuget — Swashbuckle.AspNetCore

dotnet add package Swashbuckle.AspNetCore 

.net 6 使用的是 Swashbuckle.AspNetCore

(套件依賴已預設添加在 .csproj 檔中,通常不需要自己載入)

Get start

建立 .net 6 專案

dotnet new webapi -o Demo1 -f net6.0
cd Demo1
code .

// Program.cs

啟用 Swagger

  1. 註冊服務容器

2. 使用中間件

*只在開發環境中啟用

序列化工具 System.Text.Json vs Newtonsoft

AddSwaggerGen 會依賴 System.Text.Json

如果你是使用 Newtonsoft 就需要在 AddSwaggerGen() 之後 再加上AddSwaggerGenNewtonsoftSupport()

services.AddSwaggerGen();
services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen()

註解 Comment XML

首先在 api endpoint 上方寫上需要提供給 swagger 文件資訊

*補充: 使用 vs code 開發的夥伴 可以裝這個插件 來提供 /// 註解

包含 XML 註解 IncludeXmlComments

來看看 這兩個變數分別存了什麼資訊

然後,在 .csproj檔加上這兩個 XML 標籤

  • <GenerateDocumentationFile>true</GenerateDocumentationFile> 會幫我們產生 xml 文件
  • <NoWarn>$(NoWarn);1591</NoWarn> 取消 CS1591 警告

xml 文件的所在位置和內容

*補充:未找到 xml 文件 錯誤訊息

*補充: CS1591 警告

在我們啟用 <GenerateDocumentationFile>true</GenerateDocumentationFile> 之後

專案會出現很多警告 Missing XML comment 來提醒我們尚未做 XML 註解

文件資訊 Open Api information

加上 Open api 資訊

修改前後比對 標題跟版本都不一樣了

class OpenApiInfo 還有更多可以設定的內容

*詳細內容 open api spec 有完整的定義 https://swagger.io/specification/v3/

回應類型 Describe response types

編輯 http 狀態碼 和 描述 以及產生 Example value 和 Schema

使用 XML Comment 或者 ProducesResponseTypeAttribute 都是可以的 可以擇一使用

swaggerUI:

或是使用 Swashbuckle Additional Packages

Nuget : Swashbuckle.AspNetCore.Annotations

dotnet add package Swashbuckle.AspNetCore.Annotations

啟用註解 EnableAnnotations()

把 XML Comment or ProducesResponseTypeAttribute 改成 SwaggerOperation

swagger file api endpoint 的組成

  • Summary & Description: 文字描述
  • Tags: 預設就是 controller 除非有自行另外定義
  • OperationId: 他是對於 api 端點的唯一識別,必須要全局唯一。

OperationId 在 Swagger 文件中的解釋

“OperationId is an optional unique string used to identify an operation. If provided, these IDs must be unique among all operations described in your API.”

顯示 OperationId

DisplayOperationId()

右邊會看到 OperationId

參考文件

dotnet Doc :

https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-6.0&tabs=visual-studio

github — Swashbuckle.AspNetCore : https://github.com/domaindrivendev/Swashbuckle.AspNetCore

openapi spec :

--

--