Asp .Net Core 集成 FluentValidation 强类型验证规则库

2023-12-31 00:12

本文主要是介绍Asp .Net Core 集成 FluentValidation 强类型验证规则库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 入门程序
      • 安装
      • 案例:登录
    • 验证器
      • 内置验证器
      • 自定义验证器
        • 编写自定义验证器
        • 可重复使用的属性验证器
    • 本地化
    • DI
    • 自动验证

官网: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();}}
}

测试

image

验证器

内置验证器

网站: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 强类型验证规则库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/554424

相关文章

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

C++作用域和标识符查找规则详解

《C++作用域和标识符查找规则详解》在C++中,作用域(Scope)和标识符查找(IdentifierLookup)是理解代码行为的重要概念,本文将详细介绍这些规则,并通过实例来说明它们的工作原理,需... 目录作用域标识符查找规则1. 普通查找(Ordinary Lookup)2. 限定查找(Qualif

Nginx Location映射规则总结归纳与最佳实践

《NginxLocation映射规则总结归纳与最佳实践》Nginx的location指令是配置请求路由的核心机制,其匹配规则直接影响请求的处理流程,下面给大家介绍NginxLocation映射规则... 目录一、Location匹配规则与优先级1. 匹配模式2. 优先级顺序3. 匹配示例二、Proxy_pa

使用vscode搭建pywebview集成vue项目实践

《使用vscode搭建pywebview集成vue项目实践》:本文主要介绍使用vscode搭建pywebview集成vue项目实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录环境准备项目源码下载项目说明调试与生成可执行文件核心代码说明总结本节我们使用pythonpywebv

Maven项目中集成数据库文档生成工具的操作步骤

《Maven项目中集成数据库文档生成工具的操作步骤》在Maven项目中,可以通过集成数据库文档生成工具来自动生成数据库文档,本文为大家整理了使用screw-maven-plugin(推荐)的完... 目录1. 添加插件配置到 pom.XML2. 配置数据库信息3. 执行生成命令4. 高级配置选项5. 注意事

Java集成Onlyoffice的示例代码及场景分析

《Java集成Onlyoffice的示例代码及场景分析》:本文主要介绍Java集成Onlyoffice的示例代码及场景分析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 需求场景:实现文档的在线编辑,团队协作总结:两个接口 + 前端页面 + 配置项接口1:一个接口,将o

Swagger2与Springdoc集成与使用详解

《Swagger2与Springdoc集成与使用详解》:本文主要介绍Swagger2与Springdoc集成与使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录1. 依赖配置2. 基础配置2.1 启用 Springdoc2.2 自定义 OpenAPI 信息3.

无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案

《无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案》:本文主要介绍了无法启动此程序,详细内容请阅读本文,希望能对你有所帮助... 在计算机使用过程中,我们经常会遇到一些错误提示,其中之一就是"api-ms-win-core-path-l1-1-0.dll丢失