Is it possible to skip the whole action method execution and return a specific ActionResult
when a certain condition is met in OnActionExecuting
?>
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
};
}
}