Swagger 文件加上FluentValidation驗證規則

MicroElements.Swashbuckle.FluentValidation 是一個 Swagger 擴展庫,它提供了一個便利的方法來顯示 FluentValidation
驗證器的錯誤信息,使得 Swagger API 文檔更加友好和易於使用。

具體而言,MicroElements.Swashbuckle.FluentValidation 可以自動從 FluentValidation 驗證器中提取錯誤信息,並將其顯示在
Swagger UI 的輸入欄位旁邊,以便用戶更快速地找到並修復錯誤。

MicroElements.Swashbuckle.FluentValidation

安裝方式

Nuget Package:

1
Install-Package MicroElements.Swashbuckle.FluentValidation

註冊服務

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

1
2
3
4
5

// Register Validators
builder.Services.AddValidatorsFromAssemblyContaining<Program>(ServiceLifetime.Scoped)
.AddFluentValidationAutoValidation()
.AddFluentValidationRulesToSwagger();

使用方式

如果要在 Swagger API 文檔中使用 FluentValidation 驗證 User 類型的輸入,可以為其添加一個驗證器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/// <summary>
/// CreateProductParameterValidator
/// </summary>
public class CreateProductParameterValidator : AbstractValidator<CreateProductParameter>
{

/// <summary>
/// Initializes a new instance of the <see cref="CreateProductParameterValidator"/> class.
/// </summary>
public CreateProductParameterValidator()
{
RuleFor(x => x.Name)
.NotNull()
.NotEmpty()
.WithMessage("'Name' must be not null or empty string.")
.Length(0, 50)
.WithMessage("'Name' The string length must be between 0 and 50 characters.");


RuleFor(x => x.Price)
.GreaterThanOrEqualTo(0)
.WithMessage("'Price' must be greater than or equal to zero.");
}
}

這樣,當開發人員使用 Swagger UI 查看 User 類型的 API 文檔時,就會在輸入欄位旁邊顯示相關的驗證錯誤信息,進而更方便地發現和修復錯誤。

MicroElements.Swashbuckle.FluentValidation 可以幫助開發人員更好地使用 FluentValidation 驗證器,並使得 Swagger API
文檔更加易於使用。