在全局注册操作过滤器时跳过特定操作的过滤器

Mes*_*son 10 c# asp.net-mvc-4 asp.net-web-api

我写了我自己的动作过滤器并在global.asax文件中注册,现在我的问题是我如何跳过这个过滤器的特定动作,我想通过创建一个自定义属性为例如DontValidate 并将其放在我的动作上想要跳过验证,并在我的动作过滤器代码中,我将提出一个条件,如果操作包含 DontValidate属性,则跳过验证.所以目前我还没有得到如何实现它:

下面的代码是我的验证操作过滤器

   public class ValidationActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext context)
        {
            if (context.Request.Method.ToString() == "OPTIONS") return;
            //bool dontValidate =  context.ActionDescriptor. // here im stuck how to do
            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                JsonValue errors = new JsonObject();
                foreach (var key in modelState.Keys)
                {
                    // some stuff
                }

                context.Response  = context.Request.CreateResponse<JsonValue>(HttpStatusCode.BadRequest, errors);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 26

您可以从ActionDescriptor上下文的属性中获取用于装饰控制器操作的属性列表:

public class ValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        if (context.ActionDescriptor.GetCustomAttributes<DontValidateAttribute>().Any())
        {
            // The controller action is decorated with the [DontValidate]
            // custom attribute => don't do anything.
            return;
        }

        if (context.Request.Method.ToString() == "OPTIONS") return;
        var modelState = context.ModelState;
        if (!modelState.IsValid)
        {
            JsonValue errors = new JsonObject();
            foreach (var key in modelState.Keys)
            {
                // some stuff
            }

            context.Response = context.Request.CreateResponse<JsonValue>(HttpStatusCode.BadRequest, errors);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)