介紹
驗證用戶輸入是一個Web應用中的基本功能。對于生產系統,開發人員通常需要花費大量時間,編寫大量的代碼來完成這一功能。如果我們使用FluentValidation構建ASP.NET Core Web API,輸入驗證的任務將比以前容易的多。
FluentValidation是一個非常流行的構建強類型驗證規則的.NET庫。
配置項目
第一步:下載FluentValidation
我們可以使用Nuget下載最新的 FluentValidation
庫
1
|
PM> Install-Package FluentValidation.AspNetCore |
第二步:添加FluentValidation服務
我們需要在 Startup.cs
文件中添加FluentValidation服務
1
2
3
4
5
6
7
|
public void ConfigureServices(IServiceCollection services) { // mvc + validating services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddFluentValidation(); } |
添加校驗器
FluentValidation
提供了多種內置的校驗器。在下面的例子中,我們可以看到其中的2種
- NotNull 校驗器
- NotEmpty 校驗器
第一步: 添加一個需要驗證的數據模型
下面我們添加一個 User
類。
1
2
3
4
5
6
7
|
public class User { public string Gender { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public string SIN { get ; set ; } } |
第二步: 添加校驗器類
使用 FluentValidation
創建校驗器類,校驗器類都需要繼承自一個抽象類 AbstractValidator
1
2
3
4
5
6
7
|
public class UserValidator : AbstractValidator<User> { public UserValidator() { // 在這里添加規則 } } |
第三步: 添加驗證規則
在這個例子中,我們需要驗證FirstName, LastName, SIN不能為null, 不能為空。我們也需要驗證工卡SIN(Social Insurance Number)編號是合法的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public static class Utilities { public static bool IsValidSIN( int sin) { if (sin < 0 || sin > 999999998) return false ; int checksum = 0; for ( int i = 4; i != 0; i--) { checksum += sin % 10; sin /= 10; int addend = 2 * (sin % 10); if (addend >= 10) addend -= 9; checksum += addend; sin /= 10; } return (checksum + sin) % 10 == 0; } } |
下面我們在 UserValidator
類的構造函數中,添加驗證規則
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
|
public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleFor(x => x.FirstName) .NotEmpty() .WithMessage( "FirstName is mandatory." ); RuleFor(x => x.LastName) .NotEmpty() .WithMessage( "LastName is mandatory." ); RuleFor(x => x.SIN) .NotEmpty() .WithMessage( "SIN is mandatory." ) .Must((o, list, context) => { if ( null != o.SIN) { context.MessageFormatter.AppendArgument( "SIN" , o.SIN); return Utilities.IsValidSIN( int .Parse(o.SIN)); } return true ; }) .WithMessage( "SIN ({SIN}) is not valid." ); } } |
第四步: 注入驗證服務
1
2
3
4
5
6
7
8
9
10
|
public void ConfigureServices(IServiceCollection services) { // 添加驗證器 services.AddSingleton<IValidator<User>, UserValidator>(); // mvc + validating services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddFluentValidation(); } |
第五步:在 Startup.cs
中管理你的驗證錯誤
ASP.NET Core 2.1及以上版本中,你可以覆蓋ModelState管理的默認行為(ApiBehaviorOptions)
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
30
31
32
|
public void ConfigureServices(IServiceCollection services) { // Validators services.AddSingleton<IValidator<User>, UserValidator>(); // mvc + validating services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddFluentValidation(); // override modelstate services.Configure<ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = (context) => { var errors = context.ModelState .Values .SelectMany(x => x.Errors .Select(p => p.ErrorMessage)) .ToList(); var result = new { Code = "00009" , Message = "Validation errors" , Errors = errors }; return new BadRequestObjectResult(result); }; }); } |
當數據模型驗證失敗時,程序會執行這段代碼。
在這個例子,我設置了如何向客戶端顯示錯誤。這里返回結果中,我只是包含了一個錯誤代碼,錯誤消息以及錯誤對象列表。
下面讓我們看一下最終效果。
使用驗證器
這里驗證器使用起來非常容易。
你只需要創建一個action, 并將需要驗證的數據模型放到action的參數中。
由于驗證服務已在配置中添加,因此當請求這個action時, FluentValidation
將自動驗證你的數據模型!
第一步:創建一個使用待驗證數據模型的action
1
2
3
4
5
6
7
8
9
10
|
[Route( "api/[controller]" )] [ApiController] public class DemoValidationController : ControllerBase { [HttpPost] public IActionResult Post(User user) { return NoContent(); } } |
第二步:使用POSTMAN測試你的action
總結
在本篇博客中,我講解了如何使用 FluentValidation
進行數據模型驗證。
本篇源代碼 https://github.com/lamondlu/FluentValidationExample
原文鏈接:Common features in ASP.NET Core 2.1 WebApi: Validation
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/lwqlun/p/10311945.html