net8 集成fluentvalidation

csproj

        <PackageReference Include="FluentValidation" Version="11.9.1" />
        <PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
        <PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.9.1" />

        <PackageReference Include="SharpGrip.FluentValidation.AutoValidation.Mvc" Version="1.4.0" />

program

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
   // 禁止 ASP.NET Core 在进入 Action 方法之前自动处理模型验证错误,从而允许你的 ValidateModelAttribute 过滤器捕获并处理这些错误
    options.SuppressModelStateInvalidFilter = true;
});

builder.Services.AddControllers(
    options => {
        // 400 过滤器
        options.Filters.Add<ValidateModelAttribute>(); 
    }
)
    .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<TroubleValidation>())
    ;



ValidateModelAttribute.cs

using System.Text.Json;
using ApiHelper.model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            var errMsgs = context.ModelState.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.ErrorMessage)
                .ToList();
            var response = new Response<object>()
            {
                Code = 400,
                Msg = string.Join(",", errMsgs)
            };

            context.Result = new JsonResult(response)
            {
                StatusCode = 200 // Always return 200
            };
        }
    }
}

和实体绑定的 TroubleValidation.cs

public class TroubleValidation : AbstractValidator<TroubleShootingAdd>
{
    public TroubleValidation()
    {
        // 所有的属性不为空
        RuleFor(x => x.Code).NotNull().WithMessage("Code 不能为空");
        RuleFor(x => x.TroubleName).NotNull().WithMessage("TroubleName 不能为空");
        RuleFor(x => x.Major).NotNull().WithMessage("Major 不能为空");
        RuleFor(x => x.SubSystem).NotNull().WithMessage("SubSystem 不能为空");
        RuleFor(x => x.OperationGuide).NotNull().WithMessage("OperationGuide 不能为空");
    }
}

参考: https://ravindradevrani.medium.com/fluent-validation-in-net-core-8-0-c748da274204

posted @ 2024-05-18 00:42  ifnk  阅读(13)  评论(0编辑  收藏  举报