7

With MVC4 I was able to create and register a global action filter that would check the model state prior to the action's execution and return the serialized ModelState before any damage could be done.

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
    if (!actionContext.ModelState.IsValid)
    {
        actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
    }
}

However, with MVC5, I am having trouble finding Request and therefore CreateErrorResponse

public override void OnActionExecuting(ActionExecutingContext nActionExecutingContext)
{
    if (!nActionExecutingContext.Controller.ViewData.ModelState.IsValid)
    {
        nActionExecutingContext.Result = // Where is Request.CreateErrorResponse ?
    }
}

I realize that I could create a custom response class to assign to Result but I'd rather use what's built-in if CreateErrorResponse is still available.

Any idea where I can find it relative to an ActionExecutingContext in MVC5 / Web API 2?

tacos_tacos_tacos
  • 10,277
  • 11
  • 73
  • 126
  • See this post http://stackoverflow.com/questions/11686690/handle-modelstate-validation-in-asp-net-web-api – natnael88 Jul 18 '14 at 16:32

1 Answers1

0

I know this is an old question but I recently had the same problem and solved it using

public override void OnActionExecuting(ActionExecutingContext context)
{
    if (!context.ModelState.IsValid)
    {
        context.Result = new BadRequestObjectResult(context.ModelState);
    }
}
Pete
  • 57,112
  • 28
  • 117
  • 166