Skip Filter on particular Action when action filter is registered globally

前端 未结 1 840
暖寄归人
暖寄归人 2021-02-14 16:50

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 custo

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 17:11

    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().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(HttpStatusCode.BadRequest, errors);
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题