C# .NET Core 3.1自定义模型验证与fluentvalidation
我试图通过构建一个小型测试webapi来学习.NET3.1,目前我的目标是使用fluentvalidation验证DTO,如果失败,则向调用者提供一个自定义json。我发现的和无法克服的问题有两个C# .NET Core 3.1自定义模型验证与fluentvalidation,c#,asp.net-core-3.1,fluentvalidation,model-validation,C#,Asp.net Core 3.1,Fluentvalidation,Model Validation,我试图通过构建一个小型测试webapi来学习.NET3.1,目前我的目标是使用fluentvalidation验证DTO,如果失败,则向调用者提供一个自定义json。我发现的和无法克服的问题有两个 我似乎无法通过fluentvalidation获得我写的消息(它们总是-我假设是.net核心默认的) 我似乎无法修改json化后输出给调用方的对象类型 我的代码如下: 1。控制器 [ApiController] [Route("[controller]")] publi
- 我似乎无法通过fluentvalidation获得我写的消息(它们总是-我假设是.net核心默认的)
- 我似乎无法修改json化后输出给调用方的对象类型
[ApiController]
[Route("[controller]")]
public class AdminController : ControllerBase
{
[HttpPost]
[ProducesResponseType(StatusCodes.Status409Conflict)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status202Accepted)]
public async Task<IActionResult> RegisterAccount(NewAccountInput dto)
{
return Ok();
}
}
public class NewAccountInput
{
public string Username { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public AccountType Type { get; set; }
}
public class NewAccountInputValidator : AbstractValidator<NewAccountInput>
{
public NewAccountInputValidator()
{
RuleFor(o => o.Email).NotNull().NotEmpty().WithMessage("Email vazio");
RuleFor(o => o.Username).NotNull().NotEmpty().WithMessage("Username vazio");
}
}
最后,我的配置服务
public void ConfigureServices(IServiceCollection services)
{
services
//tried both lines and it doesnt seem to work either way
.AddScoped<ApiValidationFilter>()
.AddControllers(//config=>
//config.Filters.Add(new ApiValidationFilter())
)
.AddFluentValidation(fv => {
fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;//i was hoping this did the trick
fv.RegisterValidatorsFromAssemblyContaining<NewAccountInputValidator>();
});
}
public void配置服务(IServiceCollection服务)
{
服务
//两条线路都试过了,但两条线路似乎都不起作用
.AddScope
这突出了我在atm上遇到的两个问题
这是通过asp.net core 3.15和visualstudio 16.6.3实现的。您看到的信息实际上来自FluentValidation-
您没有看到提供的自定义消息的原因是FluentValidation将显示来自链中第一个失败的验证器的验证消息,在本例中为NotNull
这提供了一些选项,用于为整个验证程序链指定单个自定义验证消息
在这种情况下,您描述的操作筛选器永远不会被命中,因为验证首先失败。要防止出现这种情况,您可以使用:
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.Configure提供了一些替代解决方案,包括配置一个InvalidModelStateResponseFactory
来执行您需要的操作
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});