Asp .Net Core 集成 FluentValidation 强类型验证规则库
官网:https://docs.fluentvalidation.net/en/latest/index.html
入门程序
安装
使用 Visual Studio 中的 NuGet 包管理器控制台运行以下命令:
Install-Package FluentValidation
或者从终端窗口使用 .net core CLI:
dotnet add package FluentValidation
案例:登录
编写通用返回类
namespace FluentValidationTest
{
public class Result
{
public string Message { get; set; }
public int Code { get; set; }
public dynamic Data { get; set; }
public static Result Success(dynamic data = null)
{
Result result = new Result();
result.Data = data;
result.Code = 1;
result.Message = "success.";
return result;
}
public static Result Fail(string message)
{
Result result = new Result();
result.Code = 0;
result.Message = message;
return result;
}
}
}
编写登录请求类
using System.ComponentModel;
namespace FluentValidationTest
{
public class LoginRequest
{
[Description("用户名")]
public string UserName { get; set; }
[Description("密码")]
public string Password { get; set; }
}
}
编写登录请求验证类
using FluentValidation;
namespace FluentValidationTest
{
public class LoginRequestValidator : AbstractValidator<LoginRequest>
{
public LoginRequestValidator()
{
RuleFor(x => x.UserName).NotEmpty().WithMessage("用户名不能为空");
RuleFor(x => x.Password).NotEmpty().WithMessage("密码不能为空");
RuleFor(x => x.Password).MinimumLength(6).MaximumLength(20).WithErrorCode("-200").WithMessage("密码长度在6-20");
}
}
}
编写用户控制器
using FluentValidation.Results;
using Microsoft.AspNetCore.Mvc;
namespace FluentValidationTest.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class UserController : ControllerBase
{
[HttpPost]
public async Task<Result> Login(LoginRequest request)
{
LoginRequestValidator validations = new LoginRequestValidator();
//验证
ValidationResult validationResult = validations.Validate(request);
if (!validationResult.IsValid)
{
return Result.Fail(validationResult.Errors[0].ErrorMessage);
}
return Result.Success();
}
}
}
测试

验证器
内置验证器
网站:https://docs.fluentvalidation.net/en/latest/built-in-validators.html
- NotNull Validator
- NotEmpty Validator
- NotEqual Validator
- Equal Validator
- Length Validator
- MaxLength Validator
- MinLength Validator
- Less Than Validator
- Less Than Or Equal Validator
- Greater Than Validator
- Greater Than Or Equal Validator
- Predicate Validator
- Regular Expression Validator
- Email Validator
- Credit Card Validator
- Enum Validator
- Enum Name Validator
- Empty Validator
- Null Validator
- ExclusiveBetween Validator
- InclusiveBetween Validator
- PrecisionScale Validator
自定义验证器
编写自定义验证器
RuleFor(x => x.UserName).Custom((userName, context) =>
{
if (!userName.Contains("admin"))
{
context.AddFailure("not amdin.");
}
});
可重复使用的属性验证器
在某些情况下,您的自定义逻辑非常复杂,您可能希望将自定义逻辑移至单独的类中。这可以通过编写一个继承抽象类的类来完成 PropertyValidator<T,TProperty>(这是 FluentValidation 的所有内置规则的定义方式)。
using FluentValidation.Validators;
using FluentValidation;
namespace FluentValidationTest
{
/// <summary>
/// 条件验证器
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TProperty"></typeparam>
public class ConditionValidator<T, TProperty> : PropertyValidator<T, TProperty>
{
Func<T, TProperty, bool> _func;
string _message;
/// <summary>
///
/// </summary>
/// <param name="func">委托</param>
/// <param name="message">提示消息</param>
public ConditionValidator(Func<T, TProperty, bool> func, string message)
{
_func = func;
_message = message;
}
public override string Name => "ConditionValidator";
public override bool IsValid(ValidationContext<T> context, TProperty value)
{
return _func.Invoke(context.InstanceToValidate, value);
}
protected override string GetDefaultMessageTemplate(string errorCode)
=> _message;
}
/// <summary>
/// 扩展类
/// </summary>
public static class ValidatorExtensions
{
public static IRuleBuilderOptions<T, TElement> Condition<T, TElement>(this IRuleBuilder<T, TElement> ruleBuilder, Func<T, TElement, bool> func, string message)
{
return ruleBuilder.SetValidator(new ConditionValidator<T, TElement>(func, message));
}
}
}
使用
RuleFor(x => x.UserName).Condition((a, b) => a.UserName.Contains("admin"),"不符合条件");
本地化
如果您想替换 FluentValidation 的全部(或部分)默认消息,则可以通过实现接口的自定义版本来实现 ILanguageManager。
例如,NotNull 验证器的默认消息是。如果您想为应用程序中验证器的所有使用替换此消息,您可以编写一个自定义语言管理器:'{PropertyName}' must not be empty.
using FluentValidation.Resources;
using FluentValidation.Validators;
namespace FluentValidationTest
{
public class CustomLanguageManager : LanguageManager
{
public CustomLanguageManager()
{
AddTranslation("en", "NotEmptyValidator", "{PropertyName} 值为空");
AddTranslation("en", "MinimumLengthValidator", "{PropertyName} {PropertyValue} 小于 {MinLength}");
}
}
}
Program 类
ValidatorOptions.Global.LanguageManager = new CustomLanguageManager();
DI
https://docs.fluentvalidation.net/en/latest/di.html
Install-Package FluentValidation.DependencyInjectionExtensions
Program.cs添加
builder.Services.AddValidatorsFromAssemblyContaining<LoginRequestValidator>();
//builder.Services.AddValidatorsFromAssembly(Assembly.Load("FluentValidationTest"));
控制器实现
public class UserController : ControllerBase
{
private LoginRequestValidator _loginRequestValidator;
public UserController(LoginRequestValidator loginRequestValidator)
{
_loginRequestValidator = loginRequestValidator;
}
}
自动验证
https://github.com/SharpGrip/FluentValidation.AutoValidation
安装 nuget 包
Install-Package SharpGrip.FluentValidation.AutoValidation.Mvc
配置
using SharpGrip.FluentValidation.AutoValidation.Mvc.Extensions;
builder.Services.AddFluentValidationAutoValidation(configuration =>
{
// Disable the built-in .NET model (data annotations) validation.
configuration.DisableBuiltInModelValidation = true;
// Only validate controllers decorated with the `FluentValidationAutoValidation` attribute.
configuration.ValidationStrategy = ValidationStrategy.Annotation;
// Enable validation for parameters bound from `BindingSource.Body` binding sources.
configuration.EnableBodyBindingSourceAutomaticValidation = true;
// Enable validation for parameters bound from `BindingSource.Form` binding sources.
configuration.EnableFormBindingSourceAutomaticValidation = true;
// Enable validation for parameters bound from `BindingSource.Query` binding sources.
configuration.EnableQueryBindingSourceAutomaticValidation = true;
// Enable validation for parameters bound from `BindingSource.Path` binding sources.
configuration.EnablePathBindingSourceAutomaticValidation = true;
// Enable validation for parameters bound from 'BindingSource.Custom' binding sources.
configuration.EnableCustomBindingSourceAutomaticValidation = true;
// Replace the default result factory with a custom implementation.
configuration.OverrideDefaultResultFactoryWith<CustomResultFactory>();
});
自定义返回结果
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SharpGrip.FluentValidation.AutoValidation.Mvc.Results;
namespace FluentValidationTest
{
public class CustomResultFactory : IFluentValidationAutoValidationResultFactory
{
public IActionResult CreateActionResult(ActionExecutingContext context, ValidationProblemDetails? validationProblemDetails)
{
return new JsonResult(Result.Fail(validationProblemDetails.Errors.Values.FirstOrDefault()[0]));
}
}
}
Asp .Net Core 集成 FluentValidation 强类型验证规则库的更多相关文章
- [Abp 源码分析]十七、ASP.NET Core 集成
0. 简介 整个 Abp 框架最为核心的除了 Abp 库之外,其次就是 Abp.AspNetCore 库了.虽然 Abp 本身是可以用于控制台程序的,不过那样的话 Abp 就基本没什么用,还是需要集合 ...
- asp.net core 集成JWT(一)
[什么是JWT] JSON Web Token(JWT)是目前最流行的跨域身份验证解决方案. JWT的官网地址:https://jwt.io/ 通俗地来讲,JWT是能代表用户身份的令牌,可以使用JWT ...
- asp.net core 集成JWT(二)token的强制失效,基于策略模式细化api权限
[前言] 上一篇我们介绍了什么是JWT,以及如何在asp.net core api项目中集成JWT权限认证.传送门:https://www.cnblogs.com/7tiny/p/11012035.h ...
- ABP官方文档翻译 6.2.1 ASP.NET Core集成
ASP.NET Core 介绍 迁移到ASP.NET Core? 启动模板 配置 启动类 模块配置 控制器 应用服务作为控制器 过滤器 授权过滤器 审计Action过滤器 校验过滤器 工作单元Acti ...
- asp.net core 集成 log4net 日志框架
asp.net core 集成 log4net 日志框架 Intro 在 asp.net core 中有些日志我们可能想输出到数据库或文件或elasticsearch等,如果不自己去实现一个 Logg ...
- Asp.Net Core 集成 Hangfire 配置使用 Redis 存储
Hangfire 官方支持 MSSQL 与 Redis(Hangfire.Pro.Redis) 两种 ,由于我的数据库是 MYSQL ,粗略查询了一下文档,现在对 .NET Core 支持的并不够好, ...
- asp.net core集成MongoDB
0.目录 整体架构目录:ASP.NET Core分布式项目实战-目录 一.前言及MongoDB的介绍 最近在整合自己的框架,顺便把MongoDBD的最简单CRUD重构一下作为组件化集成到asp.net ...
- asp.net core集成CAP(分布式事务总线)
一.前言 感谢杨晓东大佬为社区贡献的CAP开源项目,传送门在此:.NET Core 事件总线,分布式事务解决方案:CAP 以及 如何在你的项目中集成 CAP[手把手视频教程],之前也在工作中遇到分布式 ...
- asp.net core 3.x 身份验证-3cookie身份验证原理
概述 上两篇(asp.net core 3.x 身份验证-1涉及到的概念.asp.net core 3.x 身份验证-2启动阶段的配置)介绍了身份验证相关概念以及启动阶段的配置,本篇以cookie身份 ...
- asp.net core 集成 Prometheus
asp.net core 集成 prometheus Intro Prometheus 是一个开源的现代化,云原生的系统监控框架,并且可以轻松的集成 PushGateway, AlertManager ...
随机推荐
- 6.2 Sunday搜索内存特征
Sunday 算法是一种字符串搜索算法,由Daniel M.Sunday于1990年开发,该算法用于在较长的字符串中查找子字符串的位置.算法通过将要搜索的模式的字符与要搜索的字符串的字符进行比较,从模 ...
- day01 java 数据类型
数据类型 1. 数值型:整数类型 byte short int long 浮点类型 double float 基本数据类型:2.字符型:char 3.布尔型:boolean 1. ...
- 10.4 认识Capstone反汇编引擎
Capstone 是一款开源的反汇编框架,目前该引擎支持的CPU架构包括x86.x64.ARM.MIPS.POWERPC.SPARC等,Capstone 的特点是快速.轻量级.易于使用,它可以良好地处 ...
- 如何使用Arduino创建摩尔斯电码生成器
摩尔斯电码工作原理 摩尔斯电码发明于19世纪,使用非常简单的长短脉冲序列(通常为电和划)来远距离发送消息.通过将字母表中的字母编码为电和划的组合,信息可以只用一个单一的电子或声音信号来表达. 为了说明 ...
- LVGL双向链表学习笔记
LVGL双向链表学习笔记 1.LVGL链表数据类型分析 对于LVGL双向链表的使用,我们需要关注lv_ll.h和lv_ll.c两个文件,其中lv_ll.h里面包含了链表结构类型定义,以及相关API的声 ...
- Sum of MSLCM 题解
Sum of MSLCM 题目大意 定义 \(\text{MSLCM}(n)\) 为所有满足该数集的 \(\text{lcm}\) 为 \(n\) 的数集中元素个数最多的数集的所有数字的和,现有多次询 ...
- docker简单部署
docker 安装部署-yun yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docke ...
- Nginx-多功能脚本
#!/bin/bash #2020年2月16日 #auto_install_nginx_web.v3 #by fly ################################ #NGX_VER ...
- mysql查看索引利用率
-- mysql查看索引利用率 -- 如果很慢把排序去掉,加上limit 并且在where条件中限定表名. -- cardinality越接近0,利用率越低 SELECT t.TABLE_SCHEMA ...
- 编写高性能C#代码 —— Span<T>
Span 提供任意内存的连续区域的类型安全和内存安全表示形式.它是在堆栈而不是托管堆上分配的ref结构,是对任意内存块的抽象 . 1.关于Span 在NET Core 2.1中首次引入 提供对任意内存 ...