Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }
}
like image 533
George Mauer Avatar asked May 29 '13 19:05

George Mauer


People also ask

Is it possible to cancel filter execution?

You can cancel filter execution in the OnActionExecuting and OnResultExecuting methods by setting the Result property to a non-null value.

Can we override the execution order of the filters in MVC?

ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides. Using the Filter Overrides feature, we can exclude a specific action method or controller from the global filter or controller level filter. ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides.

Does .NET Web API supports action filter?

Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.


1 Answers

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;
}   
like image 58
Jason Meckley Avatar answered Oct 09 '22 11:10

Jason Meckley