Pregunta

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);
    }
}
¿Fue útil?

Solución

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;
}   

Otros consejos

Have you actually seen the example on the ASP.NET WebApi page?

Looks very much like what you're trying to achieve and all they do is setting the Response of the Context object:

If model validation fails, this filter returns an HTTP response that contains the validation errors. In that case, the controller action is not invoked.

http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

see: Handling Validation Errors

My guess is that you should throw a HttpResponseException

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top