12

我编写了自己的动作过滤器并在 global.asax 文件中注册,现在我的问题是如何跳过特定动作的过滤器,我通过为例如创建自定义属性DontValidate 并将其放置在我的动作上来考虑这一点想要跳过验证,在我的操作过滤器代码中,我会设置一个条件,如果操作包含 DontValidate属性,则跳过验证。所以目前我不知道如何实现它:

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

   public class ValidationActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext 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);
            }
        }
    }
4

1 回答 1

28

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);
        }
    }
}
于 2012-10-15T07:52:34.493 回答