net8 整合fluentvalidation

ifnk發表於2024-05-18

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

相關文章