Skip Filter on particular Action when action filte

2020-06-12 06:00发布

i'hv written my own action filter and registered in global.asax file, now my problem is how do i skip this filter for specific actions, i thought about this by creating a custom attribute for e.g DontValidate and place it over the action for which i want to skip the validation, and in my action filter code i'll put a condition that if the action contains DontValidate attribute then skip the validation. So currently i'm not getting how to implement it:

below code is my validation action filter

   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);
            }
        }
    }

1条回答
孤傲高冷的网名
2楼-- · 2020-06-12 06:24

You could get the list of attributes that were used to decorate the controller action from the ActionDescriptor property of the context:

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);
        }
    }
}
查看更多
登录 后发表回答