문제

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