您的位置:首页 > 编程语言 > ASP

ASP.NET Core WebApi中使用FluentValidation验证数据模型

2019-01-23 22:50 1636 查看

原文链接:Common features in ASP.NET Core 2.1 WebApi: Validation
作者:Anthony Giretti
译者:Lamond Lu

介绍

验证用户输入是一个Web应用中的基本功能。对于生产系统,开发人员通常需要花费大量时间,编写大量的代码来完成这一功能。如果我们使用FluentValidation构建ASP.NET Core Web API,输入验证的任务将比以前容易的多。

FluentValidation是一个非常流行的构建强类型验证规则的.NET库。

配置项目

第一步:下载FluentValidation

我们可以使用Nuget下载最新的

FluentValidation

PM> Install-Package FluentValidation.AspNetCore

第二步:添加FluentValidation服务

我们需要在

Startup.cs
文件中添加FluentValidation服务

public void ConfigureServices(IServiceCollection services)
{
// mvc + validating
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddFluentValidation();
}

添加校验器

FluentValidation
提供了多种内置的校验器。在下面的例子中,我们可以看到其中的2种

  • NotNull校验器
  • NotEmpty校验器

第一步: 添加一个需要验证的数据模型

下面我们添加一个

User
类。

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

public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
// 在这里添加规则
}
}

第三步: 添加验证规则

在这个例子中,我们需要验证FirstName, LastName, SIN不能为null, 不能为空。我们也需要验证工卡SIN(Social Insurance Number)编号是合法的

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
类的构造函数中,添加验证规则

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.");
}
}

第四步: 注入验证服务

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)

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

[Route("api/[controller]")]
[ApiController]
public class DemoValidationController : ControllerBase
{
[HttpPost]
public IActionResult Post(User user)
{
return NoContent();
}
}

第二步:使用POSTMAN测试你的action

总结

在本篇博客中,我讲解了如何使用

FluentValidation
进行数据模型验证。

本篇源代码https://github.com/lamondlu/FluentValidationExample

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐