16

我有一个预操作 web api 钩子,它将检查 ModelState.IsValid。如果 ModelState 无效,我不想执行该操作并立即返回我的消息。我该怎么做?

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

3 回答 3

36

设置 Response.Result。如果结果不为空,则不会执行该操作。确切的语法现在正在逃避我,但它很简单

if(actionContext.ModelState.IsValid == false)
{
       var response = actionContext.Request.CreateErrorResponse(...);
       actionContext.Response = response;
}   
于 2013-05-29T19:40:47.083 回答
7

你真的看过 ASP.NET WebApi 页面上的例子吗?

看起来非常像您要实现的目标,他们所做的只是设置 Context 对象的响应:

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

看:Handling Validation Errors

于 2013-05-29T20:22:52.103 回答
2

我的猜测是你应该抛出一个 HttpResponseException

于 2013-05-29T19:35:31.540 回答