Swashbuckle 與 ASP.NET Core 使用者入門
Swashbuckle 有三個主要元件:
Swashbuckle.AspNetCore.Swagger:Swagger物件模型和中介軟體,將物件公開
SwaggerDocument
為 JS ON 端點。Swashbuckle.AspNetCore.SwaggerGen:Swagger 產生器,可直接從您的路由、控制器和模型建置
SwaggerDocument
物件。 它通常會與 Swagger 端點中介軟體結合,以自動公開 Swagger JS ON。Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的內嵌版本。 它會解譯 Swagger JS ON,以建置豐富的可自訂體驗,以描述 Web API 功能。 其中包括公用方法的內建測試載入器。
套件安裝
可使用下列方法新增 Swashbuckle:
從 [套件管理員主控台] 視窗中:
移至檢視>其他 Windows>套件管理員主控台
流覽至檔案所在的目錄
.csproj
執行以下命令:
Install-Package Swashbuckle.AspNetCore -Version 6.2.3
從 [管理 NuGet 套件] 對話方塊中:
- 以滑鼠右鍵按一下[方案> 總管] 中的專案[管理 NuGet 套件]
- 將 [套件來源] 設定為 "nuget.org"
- 請確定已啟用 [包含發行前版本] 選項
- 在搜尋方塊中輸入 "Swashbuckle.AspNetCore"
- 從 [瀏覽] 索引標籤中選取最新的 "Swashbuckle.AspNetCore" 套件,並按一下 [安裝]
新增和設定 Swagger 中介軟體
將 Swagger 產生器新增至 中的 Program.cs
服務集合:
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
同時在 中 Program.cs
啟用中介軟體來提供產生的 JS ON 檔和 Swagger UI:
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
上述程式碼只有在目前的環境設定為 [開發] 時,才會新增 Swagger 中介軟體。 方法 UseSwaggerUI
呼叫會啟用 靜態檔案中介軟體。
啟動應用程式並流覽至 https://localhost:<port>/swagger/v1/swagger.json
。 描述端點的產生檔會顯示為 OpenAPI 規格 (openapi.json) 所示。
您可以在 https://localhost:<port>/swagger
找到 Swagger UI。 透過 Swagger UI 探索 API,並將其併入其他程式。
提示
若要在應用程式的根目錄 (https://localhost:<port>/
) 上提供 Swagger UI,請將 RoutePrefix
屬性設為空字串:
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.RoutePrefix = string.Empty;
});
若使用目錄搭配 IIS 或 反向 Proxy,請將 Swagger 端點設定為使用 ./
前置詞的相對路徑。 例如: ./swagger/v1/swagger.json
。 使用 /swagger/v1/swagger.json
會指示應用程式在 URL 的 true 根目錄尋找 JS ON 檔案, (加上路由前置詞,如果使用) 。 例如,請使用 https://localhost:<port>/<route_prefix>/swagger/v1/swagger.json
,而不要使用 https://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json
。
注意
根據預設,Swashbuckle 會在規格 3.0 版中產生並公開 Swagger JS ON,正式稱為 OpenAPI 規格。 若要支援回溯相容性,您可以改為選擇以 2.0 格式公開 JS ON。 此 2.0 格式對於目前支援 OpenAPI 2.0 版的 Microsoft Power Apps 和 Microsoft Flow 等整合很重要。 若要選擇使用 2.0 格式,請在 SerializeAsV2
中 Program.cs
設定 屬性:
app.UseSwagger(options =>
{
options.SerializeAsV2 = true;
});
自訂與擴充
Swagger 提供用來記載物件模型和自訂 UI 以符合佈景主題的選項。
API 資訊與描述
傳遞至 方法的 AddSwaggerGen
組態動作會新增作者、授權和描述等資訊。
在 中 Program.cs
,匯入下列命名空間以使用 類別 OpenApiInfo
:
using Microsoft.OpenApi.Models;
OpenApiInfo
使用 類別,修改 UI 中顯示的資訊:
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "ToDo API",
Description = "An ASP.NET Core Web API for managing ToDo items",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "Example Contact",
Url = new Uri("https://example.com/contact")
},
License = new OpenApiLicense
{
Name = "Example License",
Url = new Uri("https://example.com/license")
}
});
});
Swagger UI 會顯示版本資訊:
XML 註解
XML 註解可以使用下列方式啟用:
- 以滑鼠右鍵按一下 方案 總管中的專案,然後選取
Edit <project_name>.csproj
。 - 將 GenerateDocumentationFile 新增至
.csproj
檔案:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
啟用 XML 註解,可提供未記載之公用類型與成員的偵錯資訊。 未記載的類型和成員會以警告訊息表示。 例如,下列訊息指出警告碼 1591 的違規:
warning CS1591: Missing XML comment for publicly visible type or member 'TodoController'
在專案檔中定義要忽略的警告碼清單 (以分號分隔),即可隱藏警告。 將警告碼附加至 $(NoWarn);
也會套用 C# 預設值。
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
若只要針對特定成員隱藏,請將程式碼放在 #pragma 警告前置處理器指示詞中。 這個方法適用于不應該透過 API 檔公開的程式碼。在下列範例中,會忽略整個 TodoContext
類別的警告代碼 CS1591。 會在類別定義結尾處還原強制執行的警告碼。 以逗號分隔清單指定多個警告碼。
namespace SwashbuckleSample.Models;
#pragma warning disable CS1591
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options) : base(options) { }
public DbSet<TodoItem> TodoItems => Set<TodoItem>();
}
#pragma warning restore CS1591
設定 Swagger 以使用先前指示所產生的 XML 檔案。 對於 Linux 或非 Windows 作業系統,檔案名稱和路徑可以區分大小寫。 例如,檔案 TodoApi.XML
在 Windows 上有效,但不適用於 CentOS。
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "ToDo API",
Description = "An ASP.NET Core Web API for managing ToDo items",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "Example Contact",
Url = new Uri("https://example.com/contact")
},
License = new OpenApiLicense
{
Name = "Example License",
Url = new Uri("https://example.com/license")
}
});
// using System.Reflection;
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
在上述程式碼中, 反映 是用來建置符合 Web API 專案的 XML 檔案名。 AppContext.BaseDirectory 屬性用來建構 XML 檔案的路徑。 某些 Swagger 功能 (例如輸入參數的結構描述,或來自相對應屬性的 HTTP 方法和回應碼) 能在不使用 XML 文件檔案的情況下運作。 對於大部分的功能 (也就是方法摘要,以及參數和回應碼的描述) 而言,皆必須使用 XML 檔案。
透過在區段標題新增描述,對動作新增三斜線註解,可增強 Swagger UI。 在動作上方 Delete
新增摘要 > 元素: <
/// <summary>
/// Deletes a specific TodoItem.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(long id)
{
var item = await _context.TodoItems.FindAsync(id);
if (item is null)
{
return NotFound();
}
_context.TodoItems.Remove(item);
await _context.SaveChangesAsync();
return NoContent();
}
Swagger UI 會顯示上述程式碼的 <summary>
項目的內部文字:
UI 是由產生的 ON 架構所 JS 驅動:
"delete": {
"tags": [
"Todo"
],
"summary": "Deletes a specific TodoItem.",
"parameters": [
{
"name": "id",
"in": "path",
"description": "",
"required": true,
"schema": {
"type": "integer",
"format": "int64"
}
}
],
"responses": {
"200": {
"description": "Success"
}
}
},
< 將備註 >專案新增至 Create
動作方法檔。 它會補充 <summary>
項目中指定的資訊,並提供更強固的 Swagger UI。 專案 <remarks>
內容可以包含文字、 JS ON 或 XML。
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// "id": 1,
/// "name": "Item #1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(TodoItem item)
{
_context.TodoItems.Add(item);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(Get), new { id = item.Id }, item);
}
請注意使用這些額外註解的 UI 增強功能:
資料註解
以命名空間中找到 System.ComponentModel.DataAnnotations 的屬性標記模型,以協助驅動 Swagger UI 元件。
將 [Required]
屬性 (attribute) 新增至 TodoItem
類別的 Name
屬性 (property):
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SwashbuckleSample.Models;
public class TodoItem
{
public long Id { get; set; }
[Required]
public string Name { get; set; } = null!;
[DefaultValue(false)]
public bool IsComplete { get; set; }
}
此屬性的存在會變更 UI 行為,並改變基礎 JS ON 架構:
"schemas": {
"TodoItem": {
"required": [
"name"
],
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"isComplete": {
"type": "boolean",
"default": false
}
},
"additionalProperties": false
}
},
將 [Produces("application/json")]
屬性新增至 API 控制器。 其目的是要宣告控制器的動作支援回應內容類型為 application/json:
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class TodoController : ControllerBase
{
[ 媒體類型 ] 下拉式清單會選取此內容類型作為控制器 GET 動作的預設值:
當 Web API 中的資料註釋使用量增加時,UI 和 API 說明頁面會變得更清楚且更有用。
描述回應類型
取用 Web API 的開發人員最關心傳回的內容,特別是回應類型和錯誤碼,如果不是標準) ,則 (。 回應類型和錯誤碼會在 XML 註解及資料註解中表示。
Create
動作在成功時會傳回 HTTP 201 狀態碼。 張貼的要求主體為 Null 時,會傳回 HTTP 400 狀態碼。 如果 Swagger UI 中沒有適當的文件,取用者便會缺乏對這些預期結果的了解。 在下列範例中新增強調顯示的那幾行來修正該問題:
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// "id": 1,
/// "name": "Item #1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(TodoItem item)
{
_context.TodoItems.Add(item);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(Get), new { id = item.Id }, item);
}
現在,Swagger UI 清楚記載了預期的 HTTP 回應碼:
慣例可用來做為使用 明確裝飾個別動作 [ProducesResponseType]
的替代方案。 如需詳細資訊,請參閱使用 Web API 慣例。
為了支援 [ProducesResponseType]
裝飾, Swashbuckle.AspNetCore.Annotations 套件提供延伸模組來啟用和擴充回應、架構和參數中繼資料。
自訂 UI
預設 UI 可運作且可呈現。 不過,API 的文件頁面應該表示您的品牌或佈景主題。 設定 Swashbuckle 元件商標時,需要新增資源來處理靜態檔案,然後建置裝載這些檔案的資料夾結構。
啟用靜態檔案中介軟體:
app.UseHttpsRedirection();
app.UseStaticFiles();
app.MapControllers();
若要插入其他 CSS 樣式表單,請將它們新增至專案的 wwwroot 資料夾,並在中介軟體選項中指定相對路徑:
app.UseSwaggerUI(options =>
{
options.InjectStylesheet("/swagger-ui/custom.css");
});
其他資源
Swashbuckle 有三個主要元件:
Swashbuckle.AspNetCore.Swagger:Swagger 物件模型和中介軟體,以將物件公開
SwaggerDocument
為 JS ON 端點。Swashbuckle.AspNetCore.SwaggerGen:Swagger 產生器,可直接從您的路由、控制器和模型建置
SwaggerDocument
物件。 它通常會與 Swagger 端點中介軟體結合,以自動公開 Swagger JS ON。Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的內嵌版本。 它會解譯 Swagger JS ON,以建置豐富的可自訂體驗,以描述 Web API 功能。 其中包括公用方法的內建測試載入器。
套件安裝
可使用下列方法新增 Swashbuckle:
從 [套件管理員主控台] 視窗中:
移至檢視>其他 Windows>套件管理員主控台
流覽至檔案所在的目錄
TodoApi.csproj
執行以下命令:
Install-Package Swashbuckle.AspNetCore -Version 5.6.3
從 [管理 NuGet 套件] 對話方塊中:
- 以滑鼠右鍵按一下[方案總> 管] 中的專案[管理 NuGet 套件]
- 將 [套件來源] 設定為 "nuget.org"
- 請確定已啟用 [包含發行前版本] 選項
- 在搜尋方塊中輸入 "Swashbuckle.AspNetCore"
- 從 [瀏覽] 索引標籤中選取最新的 "Swashbuckle.AspNetCore" 套件,並按一下 [安裝]
新增和設定 Swagger 中介軟體
將 Swagger 產生器新增至 Startup.ConfigureServices
方法中的服務集合:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
services.AddControllers();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen();
}
在 方法中 Startup.Configure
,啟用中介軟體來提供產生的 JS ON 檔和 Swagger UI:
public void Configure(IApplicationBuilder app)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.)
app.UseSwaggerUI();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
注意
Swashbuckle 依賴 MVC 來 Microsoft.AspNetCore.Mvc.ApiExplorer 探索路由和端點。 如果專案呼叫 AddMvc ,則會自動探索路由和端點。 呼叫 AddMvcCore 時, AddApiExplorer 必須明確呼叫 方法。 如需詳細資訊,請參閱 Swashbuckle、ApiExplorer 和 Routing。
上述 UseSwaggerUI
方法呼叫會啟用靜態檔案中介軟體。 如果以 .NET Framework 或 .NET Core 1.x 為目標,請將 Microsoft.AspNetCore.StaticFiles NuGet 套件新增至專案。
啟動應用程式,並巡覽至 http://localhost:<port>/swagger/v1/swagger.json
。 描述端點的已產生檔會出現,如 openAPI 規格 (openapi.json) 所示。
您可以在 http://localhost:<port>/swagger
找到 Swagger UI。 透過 Swagger UI 探索 API,並將其併入其他程式。
提示
若要在應用程式的根目錄 (http://localhost:<port>/
) 上提供 Swagger UI,請將 RoutePrefix
屬性設為空字串:
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
若使用目錄搭配 IIS 或 反向 Proxy,請將 Swagger 端點設定為使用 ./
前置詞的相對路徑。 例如: ./swagger/v1/swagger.json
。 使用 /swagger/v1/swagger.json
會指示應用程式在 URL (和路由前置詞的 true 根目錄中尋找 JS ON 檔案,如果使用) 。 例如,請使用 http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json
,而不要使用 http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json
。
注意
根據預設,Swashbuckle 會在規格 3.0 版中產生並公開 Swagger JS ON,正式稱為 OpenAPI 規格。 若要支援回溯相容性,您可以改為選擇以 2.0 格式公開 JS ON。 此 2.0 格式對於目前支援 OpenAPI 2.0 版的 Microsoft Power Apps 和 Microsoft Flow 等整合很重要。 若要選擇使用 2.0 格式,請在 SerializeAsV2
中 Startup.Configure
設定 屬性:
public void Configure(IApplicationBuilder app)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(c =>
{
c.SerializeAsV2 = true;
});
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
自訂與擴充
Swagger 提供用來記載物件模型和自訂 UI 以符合佈景主題的選項。
在 Startup
類別中,加入下列命名空間:
using System;
using System.Reflection;
using System.IO;
API 資訊與描述
傳遞至 AddSwaggerGen
方法的組態動作會新增作者、授權和描述等資訊:
在 Startup
類別中,匯入下列命名空間以使用 OpenApiInfo
類別:
using Microsoft.OpenApi.Models;
使用 類別 OpenApiInfo
,修改 UI 中顯示的資訊:
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "ToDo API",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "Shayne Boyer",
Email = string.Empty,
Url = new Uri("https://twitter.com/spboyer"),
},
License = new OpenApiLicense
{
Name = "Use under LICX",
Url = new Uri("https://example.com/license"),
}
});
});
Swagger UI 會顯示版本資訊:
XML 註解
XML 註解可以使用下列方式啟用:
- 以滑鼠右鍵按一下 方案總 管中的專案,然後選取
Edit <project_name>.csproj
。 - 手動將反白顯示的行新增至
.csproj
檔案:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
啟用 XML 註解,可提供未記載之公用類型與成員的偵錯資訊。 未記載的類型和成員會以警告訊息表示。 例如,下列訊息指出警告碼 1591 的違規:
warning CS1591: Missing XML comment for publicly visible type or member 'TodoController.GetAll()'
在專案檔中定義要忽略的警告碼清單 (以分號分隔),即可隱藏警告。 將警告碼附加至 $(NoWarn);
也會套用 C# 預設值。
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
若只要針對特定成員隱藏,請將程式碼放在 #pragma 警告前置處理器指示詞中。 這個方法適用于不應該透過 API 檔公開的程式碼。在下列範例中,會忽略整個 Program
類別的警告代碼 CS1591。 會在類別定義結尾處還原強制執行的警告碼。 以逗號分隔清單指定多個警告碼。
namespace TodoApi
{
#pragma warning disable CS1591
public class Program
{
public static void Main(string[] args) =>
BuildWebHost(args).Run();
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
#pragma warning restore CS1591
}
設定 Swagger 以使用先前指示所產生的 XML 檔案。 對於 Linux 或非 Windows 作業系統,檔案名稱和路徑可以區分大小寫。 例如,檔案 TodoApi.XML
在 Windows 上有效,但不適用於 CentOS。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
services.AddControllers();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "ToDo API",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "Shayne Boyer",
Email = string.Empty,
Url = new Uri("https://twitter.com/spboyer"),
},
License = new OpenApiLicense
{
Name = "Use under LICX",
Url = new Uri("https://example.com/license"),
}
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}
在上述程式碼中, 反映 是用來建置符合 Web API 專案的 XML 檔案名。 AppContext.BaseDirectory 屬性用來建構 XML 檔案的路徑。 某些 Swagger 功能 (例如輸入參數的結構描述,或來自相對應屬性的 HTTP 方法和回應碼) 能在不使用 XML 文件檔案的情況下運作。 對於大部分的功能 (也就是方法摘要,以及參數和回應碼的描述) 而言,皆必須使用 XML 檔案。
透過在區段標題新增描述,對動作新增三斜線註解,可增強 Swagger UI。 在動作上方 Delete
新增摘要 > 元素: <
/// <summary>
/// Deletes a specific TodoItem.
/// </summary>
/// <param name="id"></param>
[HttpDelete("{id}")]
public IActionResult Delete(long id)
{
var todo = _context.TodoItems.Find(id);
if (todo == null)
{
return NotFound();
}
_context.TodoItems.Remove(todo);
_context.SaveChanges();
return NoContent();
}
Swagger UI 會顯示上述程式碼的 <summary>
項目的內部文字:
UI 是由產生的 ON 架構所 JS 驅動:
"delete": {
"tags": [
"Todo"
],
"summary": "Deletes a specific TodoItem.",
"operationId": "ApiTodoByIdDelete",
"consumes": [],
"produces": [],
"parameters": [
{
"name": "id",
"in": "path",
"description": "",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "Success"
}
}
}
< 將備註 >專案新增至 Create
動作方法檔。 它會補充 <summary>
項目中指定的資訊,並提供更強固的 Swagger UI。 專案 <remarks>
內容可以包含文字、 JS ON 或 XML。
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// "id": 1,
/// "name": "Item1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<TodoItem> Create(TodoItem item)
{
_context.TodoItems.Add(item);
_context.SaveChanges();
return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
請注意使用這些額外註解的 UI 增強功能:
資料註解
以命名空間中找到 System.ComponentModel.DataAnnotations 的屬性標記模型,以協助驅動 Swagger UI 元件。
將 [Required]
屬性 (attribute) 新增至 TodoItem
類別的 Name
屬性 (property):
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace TodoApi.Models
{
public class TodoItem
{
public long Id { get; set; }
[Required]
public string Name { get; set; }
[DefaultValue(false)]
public bool IsComplete { get; set; }
}
}
此屬性的存在會變更 UI 行為,並改變基礎 JS ON 架構:
"definitions": {
"TodoItem": {
"required": [
"name"
],
"type": "object",
"properties": {
"id": {
"format": "int64",
"type": "integer"
},
"name": {
"type": "string"
},
"isComplete": {
"default": false,
"type": "boolean"
}
}
}
},
將 [Produces("application/json")]
屬性新增至 API 控制器。 其目的是要宣告控制器的動作支援回應內容類型為 application/json:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
private readonly TodoContext _context;
[ 回應內容類型 ] 下拉式清單會選取此內容類型作為控制器 GET 動作的預設值:
當 Web API 中的資料註釋使用量增加時,UI 和 API 說明頁面會變得更清楚且更有用。
描述回應類型
使用 Web API 的開發人員最關心傳回的內容,特別是回應類型和錯誤碼,如果不是標準) ,則 (。 回應類型和錯誤碼會在 XML 註解及資料註解中表示。
Create
動作在成功時會傳回 HTTP 201 狀態碼。 張貼的要求主體為 Null 時,會傳回 HTTP 400 狀態碼。 如果 Swagger UI 中沒有適當的文件,取用者便會缺乏對這些預期結果的了解。 在下列範例中新增強調顯示的那幾行來修正該問題:
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// "id": 1,
/// "name": "Item1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<TodoItem> Create(TodoItem item)
{
_context.TodoItems.Add(item);
_context.SaveChanges();
return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
現在,Swagger UI 清楚記載了預期的 HTTP 回應碼:
在 ASP.NET Core 2.2 或更新版本中,慣例可作為使用 [ProducesResponseType]
明確裝飾個別動作的替代方案。 如需詳細資訊,請參閱使用 Web API 慣例。
為了支援裝飾 [ProducesResponseType]
, Swashbuckle.AspNetCore.Annotations 套件提供延伸模組來啟用和擴充回應、架構和參數中繼資料。
自訂 UI
預設 UI 同時為功能且可呈現。 不過,API 的文件頁面應該表示您的品牌或佈景主題。 設定 Swashbuckle 元件商標時,需要新增資源來處理靜態檔案,然後建置裝載這些檔案的資料夾結構。
如果以 .NET Framework 或 .NET Core 1.x 為目標,請將 Microsoft.AspNetCore.StaticFiles NuGet 套件新增至您的專案:
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
如果以 .NET Core 2.x 為目標並使用中繼套件,則已安裝上述 NuGet 套件。
啟用靜態檔案中介軟體:
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
若要插入其他 CSS 樣式表單,請將它們新增至專案的 wwwroot 資料夾,並在中介軟體選項中指定相對路徑:
app.UseSwaggerUI(c =>
{
c.InjectStylesheet("/swagger-ui/custom.css");
}