简体   繁体   English

Asp.net 核心 API 方法调用流利 api 验证失败

[英]Asp.net core API method is called on fluent api validation failed

I have implemented Fluent API validation with Aspnet Core and MediatR and disabled the default MVC validation.我已经使用 Aspnet Core 和 MediatR 实现了 Fluent API 验证,并禁用了默认的 MVC 验证。 Previously, On invalid data, the API validation will be called first and then API method will be called.以前,在无效数据上,首先调用 API 验证,然后调用 API 方法。

On invalid data, Fluent API Validation will throw an error and the call won't fired to the api method.在无效数据上,Fluent API 验证将引发错误,并且不会触发对 api 方法的调用。

But now, even on invalid data, the api method is called.但是现在,即使在无效数据上,也会调用 api 方法。 what am I missing?我错过了什么?

Configuration:配置:

services.AddMvc().AddFluentValidation(fv =>
        {
            fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
        });
        ValidatorOptions.Global.CascadeMode = CascadeMode.StopOnFirstFailure;
        services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());

Code:代码:

public class LoginCommandValidator : AbstractValidator<LoginCommand>
        {
            public LoginCommandValidator(IStringLocalizer<Resource> stringLocalizer)
            {
                this.CascadeMode = CascadeMode.StopOnFirstFailure;
    
                RuleFor(v => v.Username)
                    .NotEmpty().WithMessage(stringLocalizer["InvalidUsername"])
                    .NotNull().WithMessage(stringLocalizer["InvalidUsername"]);
    
                RuleFor(v=>v.Password)
                    .NotEmpty().WithMessage(stringLocalizer["InvalidPassword"])
                    .NotNull().WithMessage(stringLocalizer["InvalidPassword"]);
            }
        }

Maybe you can write an ActionFilterAttribute, and then add this filter to your Controller.也许您可以编写一个 ActionFilterAttribute,然后将此过滤器添加到您的 Controller 中。 Like this:像这样:

 public class ValidateModelStateFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreteErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

Then add this filter above your controller:然后在您的 controller 上方添加此过滤器:

[ValidateModelStateFilter]

Hope this can help you.希望这可以帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM