Swagger 文件加上範例格式資料

Swashbuckle.AspNetCore.Filters 是一個 Swagger 擴充庫,提供一組有用的Attribute和工具,可以幫助開發人員更輕鬆地使用 Swagger
和 .NET Core 開發 Web API。

其中的 ExampleProvider 是一個介面,用於定義如何生成 Swagger API 文檔中的範例資料。具體而言,ExampleProvider
提供了一種方法,即 GetExamples(),該方法返回物件,其中包含要顯示在 Swagger API 文檔中的示例數據。通常,開發人員可以實現自己的
ExampleProvider,並使用自定義的邏輯生成範例資料。

Swashbuckle.AspNetCore.Filters

安裝方式

Nuget Package:

1
Install-Package Swashbuckle.AspNetCore.Filters

註冊服務

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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."
}
);


// Swashbuckle.AspNetCore.Filters
options.ExampleFilters();

var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
})
// Swashbuckle.AspNetCore.Filters Add Swagger Examples
.AddSwaggerExamplesFromAssemblyOf<Program>();

使用方式

建立類別去實作IExamplesProvider<T>.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

/// <summary>
/// The create product parameter example class
/// </summary>
/// <seealso cref="IExamplesProvider{CreateProductParameter}"/>
public class CreateProductParameterExample : IExamplesProvider<CreateProductParameter>
{
/// <summary>
/// Gets the examples
/// </summary>
/// <returns>The create product parameter</returns>
public CreateProductParameter GetExamples()
{
var createProductParameter = new CreateProductParameter
{
Name = "Blue Striped Shirt",
Description = "A blue and white striped shirt, great for a casual day out.",
Price = 29.99M,
Brand = "H&M",
Category = "Clothing",
Color = "Blue",
Size = "M",
Material = "Cotton",
};

return createProductParameter;
}
}

可以在 Action 方法上添加 [SwaggerRequestExample],以提供請求範例資料,方便 Swagger 文檔中的使用者了解 API 的使用方式。

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

/// <summary>
/// 建立新的產品。
/// </summary>
/// <param name="parameter">建立產品的參數。</param>
/// <returns>包含成功或失敗資訊的建立產品結果輸出模型。</returns>
[HttpPost]
[SwaggerRequestExample(typeof(CreateProductParameter), typeof(CreateProductParameterExample))]
public async Task<IActionResult> Create([FromBody]CreateProductParameter parameter)
{

return Ok();
}


這樣,當開發人員使用 Swagger UI 查看 User 類型的 API 文檔時,就會顯示剛剛定義的示例數據。這樣做能夠更好地幫助開發人員理解
API 的使用方式,進而提高開發效率和品質。