Web Api - how to stop the web pipeline directly from an OnActionExecuting Filter

George Mauer picture George Mauer · May 29, 2013 · Viewed 16.2k times · Source

I have a pre-action web api hook that will check ModelState.IsValid. If the ModelState is not valid I do not want to execute the action and just return my message immediately. How exactly do I do this?

public class ValidateModelStateAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) {
        if (!actionContext.ModelState.IsValid)
        {
            var msg = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            // Now What?
        }
        base.OnActionExecuting(actionContext);
    }
}

Answer

Jason Meckley picture Jason Meckley · May 29, 2013

set the Response.Result. If the result is not null it will not execute the action. the exact syntax is escaping me right now, but it's as simple as

if(actionContext.ModelState.IsValid == false)
{
       var response = actionContext.Request.CreateErrorResponse(...);
       actionContext.Response = response;
}