首页 > 编程语言 >Asp .Net Core 集成 FluentValidation 强类型验证规则库

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

时间:2023-12-30 22:44:07浏览次数:43  
标签:Core Asp string 验证 FluentValidation Validator using public

目录
官网: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]));
        }
    }
}

标签:Core,Asp,string,验证,FluentValidation,Validator,using,public
From: https://www.cnblogs.com/vic-tory/p/17936995

相关文章

  • Ftp基础(五):.NetCore中使用Ftp的建议(FluentFTP)
      上一篇说道C#使用FluentFTP来简单的连接使用Ftp,本篇是个人在.NetCore中使用Ftp的建议(可能有点啰嗦):  1、为Ftp的配置创建基类  在开发过程中,我们如果要使用Ftp,往往需要这几个信息:  Host:Ftp地址Port:端口号User:用户名Password:密码WorkingDirect......
  • ASP.NET Core MiniAPI中 EndPoint相关
    1.状态码返回之演化之路1.1最基本的就是用Results或者TypedResults返回带有状态码的响应(可选Json响应体)app.MapGet("/fruit/{id}",(stringid)=>{if(_fruit.TryGetValue(id,outFruitfruit)){returnResults.Ok(fruit)......
  • .Net Core WebAPI 缓存
    Asp.NetCoreWebAPI缓存 一、缓存缓存指在中间层中存储数据的行为,该行为可使后续数据检索更快。从概念上讲,缓存是一种性能优化策略和设计考虑因素。缓存可以显著提高应用性能,方法是提高不常更改(或检索成本高)的数据的就绪性。二、RFC9111在最新的缓存控制规范文件RFC91......
  • ASP.NET Core 6(.NET 6) Program.cs中使用读取appsettings.json配置文件
    ​ 在ASP.NETCore6(.NET6)中,可以使用Json格式的appsettings.json配置文件来配置应用程序,用于存储应用程序的配置信息,方便我们灵活的配置应用程序。本文主要介绍Program.cs中,使用读取appsettings.json配置文件的方法,以及相关的示例代码。1、通过配置实体类的方式1)配置实体......
  • .net core 单元测试项目搭建
    背景和目的为了提高系统稳定性,通常我们有两方面的计划:黑盒测试:自动化测试,以接口来主体,通过控制入参的形式,检验出参,来模拟用户在线上的实际业务;(可以覆盖绝大部分的业务)白盒测试:单元测试,以关键逻辑方法为主体,通过控制入参的形式,检验数据变化,站在开发的角度上来模拟实际调用(可以......
  • Taurus .Net Core 微服务开源框架:Admin 插件【4-8】 - 配置管理-Mvc【Plugin-Limit 接
    前言:继上篇:Taurus.NetCore微服务开源框架:Admin插件【4-7】-配置管理-Mvc【Plugin-Metric接口调用次数统计】本篇继续介绍下一个内容:1、系统配置节点:Mvc- Plugin-Limit接口访问限制、IP限制、Ack限制:配置界面如下:限制目前提供以下三个类别的限制:1、Rate访......
  • 在不受支持的 Mac 上安装 macOS Sonoma (OpenCore Legacy Patcher)
    在不受支持的Mac上安装macOSSonoma、Ventura、Monterey、BigSur(OpenCoreLegacyPatcher)InstallmacOSonunsupportedMacs作者主页:sysin.orgmacOSSonoma正式版已发布,OpenCoreLegacyPatcherv1.0.0版本已支持。随着OpenCoreLegacyPatcher1.0.0的发布,OLP项目组......
  • linux下java调用netcore程序
    代码备份仅供参考自述文件#JavaCallCSharpJavacallC#libbuildwith.NETCORE2.0viaC++aswraperThecodeisbasedon[examplefromcoreCLR](https://github.com/dotnet/coreclr/tree/master/src/coreclr/hosts/unixcoreruncommon)JavausingJNItocallC++......
  • Linux下netcore调用java代码
    代码备份,仅供参考自述文件#CSharpCallJavaC#invokeJavaviaC++asawraper.C#invokeC++viaP/invoke.C++startsaJVMtoruntheJavacode.C#codeshouldbecompiledin.NETcore2.0YoushouldedittheMakefiletosetthePathofJavaSDKexpor......
  • Asp.net WebApi Swagger Tag 标记分组归纳显示Api接口路由
    官方文档说明地址https://swagger.io/docs/specification/2-0/grouping-operations-with-tags/创建一个自定义的特性类publicclassControllerGroupAttribute:Attribute{publicControllerGroupAttribute(stringgroupName){if......