Swagger 文件安裝與設定

現今許多 Web API 開發團隊都採用 Swagger 來製作 API 文件,這讓開發人員能夠更加便利地開發和測試 API。使用 Swagger
的好處包括但不限於:清楚的 API 規範、易於閱讀的 API 文件、快速的 API 測試等。此外,Swagger 還支援自動生成客戶端程式碼,使得開發人員能夠更快地建立與
API 互動的應用程式。

Swashbuckle.AspNetCore

安裝方式

Nuget Package:

1
Install-Package Swashbuckle.AspNetCore

註冊服務

Program.cs 中 Dependency Injection 加上以下的程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc
(
"v1",
new OpenApiInfo()
{
Title = " Product Open API",
Version = new Version(1, 0).ToString(),
Description = "This is Product API Swagger Document."
}
);

var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

在Program.cs之中的Middleware加上

1
2
3
4

app.UseSwagger();
app.UseSwaggerUI();

使用方式

MIME Types

MIME (Multipurpose Internet Mail Extensions) 類型是一種標準的 Internet 媒體類型,它用於標識在互聯網上傳輸的各種文件格式。以下是一些常見的
MIME 類型:

  • text/plain:純文字格式
  • text/html:HTML 網頁格式
  • application/json:JSON 格式
  • application/xml:XML 格式
  • multipart/form-data:用於表單提交的數據格式

Controller之中加上 ConsumesAttribute.csProducesAttribute.cs,可以在Request及Response 指定 MIME Type。

1
2
3
4
5
6
7
8
9
10
11

[ApiController]
[Route("api/[controller]")]
[Consumes(MediaTypeNames.Application.Json)]
[Produces(MediaTypeNames.Application.Json)]
public class WeatherForecastController : ControllerBase
{

}


Produces Response Type

[ProducesResponseType] 可用於指定 API 方法的輸出類型和狀態碼。在這個例子中,[ProducesResponseType] 屬性指定了三種不同的輸出類型和狀態碼:

  • 如果 API 方法返回的是 ResultOutputModel 類型,且狀態碼為 200 OK,那麼 Swagger 將顯示 ResultOutputModel 類型的數據結構,以及
    200 OK 狀態碼的相關信息。

  • 如果 API 方法返回的是 FailureResultOutputModel 類型,且狀態碼為 400 Bad Request,那麼 Swagger 將顯示
    FailureResultOutputModel 類型的數據結構,以及 400 Bad Request 狀態碼的相關信息。

  • 如果 API 方法返回的是 FailureResultOutputModel 類型,且狀態碼為 404 Not Found,那麼 Swagger 將顯示
    FailureResultOutputModel 類型的數據結構,以及 404 Not Found 狀態碼的相關信息

1
2
3
4
5
6
7
8
9
10
11
12

[HttpPost]
[ProducesResponseType(typeof(ResultOutputModel), 200)]
[ProducesResponseType(typeof(FailureResultOutputModel), 400)]
[ProducesResponseType(typeof(FailureResultOutputModel), 404)]
public async Task<IActionResult> CreateAsync([FromBody]CreateCustomerRequest createCustomerRequest)
{

return Ok();
}


Header加上參數

當API需要一些Header進行授權等行為時候。Swagger需要做一些調整。舉例來說當Request需要在Header之中的Token進行驗證的時候可以這樣做。

建立 AddHeaderParameterOperationFilter.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class AddHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
{
operation.Parameters = new List<OpenApiParameter>();
}

operation.Parameters.Add(new OpenApiParameter
{
Name = "Token",
In = ParameterLocation.Header,
Required = true,
Example = new OpenApiString("")
});
}
}

之後在Progarm.cs的DI註冊加上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
builder.Services.AddSwaggerGen(options =>
{

options.SwaggerDoc
(
"v1",
new()
{
Title = " Product Open API",
Version = new Version(1, 0).ToString(),
Description = "This is Product API Swagger Document."
}
);

var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));

// 加上這一行
options.OperationFilter<AddHeaderParameterOperationFilter>();
});