سؤال

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);
    }
}
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top