ASP.NET Core WebApi中使用FluentValidation验证数据模型
原文链接: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
ASP.NET Core WebApi中使用FluentValidation验证数据模型的更多相关文章
- ASP.NET Core WebAPI中的分析工具MiniProfiler
介绍 作为一个开发人员,你知道如何分析自己开发的Api性能么? 在Visual Studio和Azure中, 我们可以使用Application Insight来监控项目.除此之外我们还可以使用一个免 ...
- Asp.Net Core WebApi中接入Swagger组件(初级)
开发WebApi时通常需要为调用我们Api的客户端提供说明文档.Swagger便是为此而存在的,能够提供在线调用.调试的功能和API文档界面. 环境介绍:Asp.Net Core WebApi + S ...
- .NET Core:在ASP.NET Core WebApi中使用Cookie
一.Cookie的作用 Cookie通常用来存储有关用户信息的一条数据,可以用来标识登录用户,Cookie存储在客户端的浏览器上.在大多数浏览器中,每个Cookie都存储为一个小文件.Cookie表示 ...
- ASP.NET Core WebAPI中使用JWT Bearer认证和授权
目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...
- Asp.Net Core WebAPI中启用XML格式数据支持
因为XML是一种非常常用的数据格式,所以Asp.Net core提供了非常便利的方式来添加对XML格式的支持 只需要在IOC注册Controller服务的后面跟上.AddXmlDataContract ...
- ASP.NET Core WebApi中简单像素转换跟踪实现
像素跟踪虽然是最早用于跟踪营销转换的方法,但它仍然被广泛使用,像Facebook这样的大公司仍然将其视为跟踪网页转换的方法之一. 由于它的简单性,通过像素方法的跟踪转换仍然被广泛使用.它不需要任何复杂 ...
- ASP.NET Core WebApi基于Redis实现Token接口安全认证
一.课程介绍 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NET WebSer ...
- Asp.net core WebApi 使用Swagger生成帮助页
最近我们团队一直进行.net core的转型,web开发向着前后端分离的技术架构演进,我们后台主要是采用了asp.net core webapi来进行开发,开始每次调试以及与前端人员的沟通上都存在这效 ...
- ASP.NET Core WebApi使用Swagger生成api说明文档看这篇就够了
引言 在使用asp.net core 进行api开发完成后,书写api说明文档对于程序员来说想必是件很痛苦的事情吧,但文档又必须写,而且文档的格式如果没有具体要求的话,最终完成的文档则完全取决于开发者 ...
随机推荐
- machine learning 之 Anomaly detection
自Andrew Ng的machine learning课程. 目录: Problem Motivation Gaussian Distribution Algorithm Developing and ...
- I/O-----字符输入流
今天学习了字符流 ,果不其然又和以前的搞混了 package io.day04; import java.io.FileReader; import java.io.FileWriter; impo ...
- http_server.go
, fmt.Sprintf("%s: closing %s", proto, listener.Addr())) }
- nsqlookupd.go
) } l.Lock() l.httpListener = httpListener l.Unlock() httpServer := newHTTPServe ...
- Bootstrap 小结
Bootstrap 小结 Bootstrap4特点:1.兼容IE10+ 2.使用flexbox 布局 3.抛弃Nomalize.css 4.提供布局和 reboot 版本 Bootstrap组成:1. ...
- python struct.pack() 二进制文件,文件中打包二进制数据的存储与解析
学习Python的过程中,遇到一个问题,在<Python学习手册>(也就是<learning python>)中,元组.文件及其他章节里,关于处理二进制文件里,有这么一段代码的 ...
- 虚拟机console基础环境配置——安装VMware Tools
1. 虚拟机设置中点击安装2. 虚拟机中挂载VMware Tools镜像3. 解压安装4. 配置共享目录5. 有关VMware Tools 1. 虚拟机设置中点击安装 VMware workstati ...
- enumerate取下标
for index,item in enumerate(product_list): # print(product_list.index(item),item) print(index,item) ...
- Ubuntu配置tomcat9
buntu 安装jdk:[链接] Ubuntu安装eclipse:[链接] Ubuntu下安装MySQL与mysql workbench:[链接] Ubuntu配置tomcat9:[链接] Ubunt ...
- nginx用户认证与htpasswd命令
最近在搭建ELK,然后ELK的kibana界面想添加一个访问限制,看到kibana有个插件x-pack,本来想用用,发现是收费的,就放弃了,然后就想着想配置下nginx的认证访问来实现简单的访问登陆. ...