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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方

SpringBoot集成XXL-JOB实现任务管理全流程

《SpringBoot集成XXL-JOB实现任务管理全流程》XXL-JOB是一款轻量级分布式任务调度平台,功能丰富、界面简洁、易于扩展,本文介绍如何通过SpringBoot项目,使用RestTempl... 目录一、前言二、项目结构简述三、Maven 依赖四、Controller 代码详解五、Service

python中的显式声明类型参数使用方式

《python中的显式声明类型参数使用方式》文章探讨了Python3.10+版本中类型注解的使用,指出FastAPI官方示例强调显式声明参数类型,通过|操作符替代Union/Optional,可提升代... 目录背景python函数显式声明的类型汇总基本类型集合类型Optional and Union(py

MySQL中查询和展示LONGBLOB类型数据的技巧总结

《MySQL中查询和展示LONGBLOB类型数据的技巧总结》在MySQL中LONGBLOB是一种二进制大对象(BLOB)数据类型,用于存储大量的二进制数据,:本文主要介绍MySQL中查询和展示LO... 目录前言1. 查询 LONGBLOB 数据的大小2. 查询并展示 LONGBLOB 数据2.1 转换为十

springboot2.1.3 hystrix集成及hystrix-dashboard监控详解

《springboot2.1.3hystrix集成及hystrix-dashboard监控详解》Hystrix是Netflix开源的微服务容错工具,通过线程池隔离和熔断机制防止服务崩溃,支持降级、监... 目录Hystrix是Netflix开源技术www.chinasem.cn栈中的又一员猛将Hystrix熔

MyBatis-Plus 与 Spring Boot 集成原理实战示例

《MyBatis-Plus与SpringBoot集成原理实战示例》MyBatis-Plus通过自动配置与核心组件集成SpringBoot实现零配置,提供分页、逻辑删除等插件化功能,增强MyBa... 目录 一、MyBATis-Plus 简介 二、集成方式(Spring Boot)1. 引入依赖 三、核心机制

SpringBoot集成P6Spy的实现示例

《SpringBoot集成P6Spy的实现示例》本文主要介绍了SpringBoot集成P6Spy的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录本节目标P6Spy简介抛出问题集成P6Spy1. SpringBoot三板斧之加入依赖2. 修改