我有一个pre-action web api hook,它将检查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);
}
}
答案 0 :(得分:33)
设置Response.Result。如果结果不为null,则不会执行该操作。确切的语法现在正在逃避我,但它就像
一样简单if(actionContext.ModelState.IsValid == false)
{
var response = actionContext.Request.CreateErrorResponse(...);
actionContext.Response = response;
}
答案 1 :(得分:7)
您是否真的在ASP.NET WebApi页面上看到了这个示例?
看起来非常像你想要实现的目标,他们所做的就是设置Context对象的Response:
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
答案 2 :(得分:2)
我的猜测是你应该抛出一个HttpResponseException