How to skip action execution from an ActionFilter?

前端 未结 4 580
轮回少年
轮回少年 2020-12-09 01:10

Is it possible to skip the whole action method execution and return a specific ActionResult when a certain condition is met in OnActionExecuting?

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 01:51

    If anyone is extending ActionFilterAttribute in MVC 5 API, then you must be getting HttpActionContext instead of ActionExecutingContext as the type of parameter. In that case, simply set httpActionContext.Response to new HttpResponseMessage and you are good to go.

    I was making a validation filter and here is how it looks like:

        /// 
        /// Occurs before the action method is invoked.
        /// This will validate the request
        /// 
        /// The http action context.
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ApiController ctrl = (actionContext.ControllerContext.Controller as ApiController);
            if (!ctrl.ModelState.IsValid)
            {
                var s = ctrl.ModelState.Select(t => new { Field = t.Key, Errors = t.Value.Errors.Select(e => e.ErrorMessage) });
                actionContext.Response = new System.Net.Http.HttpResponseMessage()
                {
                    Content = new StringContent(JsonConvert.SerializeObject(s)),
                    ReasonPhrase = "Validation error",
                    StatusCode = (System.Net.HttpStatusCode)422
                };
            }
        }
    

提交回复
热议问题