1,nuget增加 FluentValidation.AspNetCore 2. DI中添加 builder.Services.AddFluentValidation(opt=>{ opt.RegisterValidatorsFromAssembly( Assembly.GetEntryAssembly()); }); 3. 添加具体的校验类 using FluentValidation; namespace EShopWebApi.Controllers; public class UserUpdateRequestValidator : AbstractValidator<UserUpdateRequest> { public UserUpdateRequestValidator() { RuleFor(c=>c.Name).MaximumLength(2).WithErrorCode("403").WithMessage("Name长度不能超过2"); } }
其他代码:
using Microsoft.AspNetCore.Mvc; [ApiController] [Route("[controller]")] public class TestController { [HttpPost("Test")] public async Task<ActionResult<string>> Test([FromBody] UserUpdateRequest request) { return await Task.FromResult("sd"); } }
using System.ComponentModel.DataAnnotations; public class UserUpdateRequest{ // 这种校验与实体类耦合 // [MaxLength(2)] public string Name { get; set; } public int Age { get; set; } }
标签:Name,FluentValidation,校验,class,using,net,public From: https://www.cnblogs.com/Insist-Y/p/17450391.html