如果modelstate无效,则动作过滤器不运行 [英] Action Filter does not run if modelstate is not valid

查看:60
本文介绍了如果modelstate无效,则动作过滤器不运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个自定义操作过滤器,该过滤器应拦截modelstate并根据当前状态(有效或无效)执行某些操作.但是,经过一些检查之后,我意识到动作过滤器仅在modelstate已经有效的情况下才运行.如果存在输入视图模型的所有条目.

I am trying to build a custom action filter that is supposed to intercept the modelstate and do something depending on the current state (valid or invalid). However, after doing some checks, I realized that the action filter only runs if the modelstate is already valid ie. If all the entries of an input viewmodel are present.

一个例子是我的身份验证json.它具有用户名,密码和密钥.

An example is my authentication json. It has username,password and secret key.

{
    "Email": "user@apppp.com",
    "Password": "password",
    "SecretKey":""
}

上面的一个是modelstate无效的,因为需要密钥.因此,动作过滤器无法运行

The one above is modelstate invalid because secret key is required. Thus the action filter does not run

{
    "Email": "user@apppp.com",
    "Password": "password",
    "SecretKey":"abc"
}

这第二个是模型状态有效的,因此动作过滤器运行.但是,我想做的是触发我的动作过滤器,即使该过滤器无效.我该如何覆盖?

This second one is modelstate valid thus the action filter runs. However, what I want to do is trigger my action filter even if its invalid. How can I overwrite that?

ActionFilter

ActionFilter

public class ModelValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            //context.Result = new ValidationFailedResult(context.ModelState);
            context.Result = new OkObjectResult("Hello");
        }
        else
        {
            context.Result = new OkObjectResult("Bye");
        }
    }
}

推荐答案

ASP.NET Core 2.1 comes with an [ApiController] attribute which is used in the default templates and will add model validation to all actions of the given controller.

可以在启动过程中通过 ApiBehaviorOptions 全局禁用它:

It can be disabled globally via ApiBehaviorOptions during Startup:

services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});

这篇关于如果modelstate无效,则动作过滤器不运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆