我有一个 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);
}
}
最佳答案
设置 Response.Result。如果结果不为空,则不会执行该操作。确切的语法现在正在逃避我,但它就像
if(actionContext.ModelState.IsValid == false)
{
var response = actionContext.Request.CreateErrorResponse(...);
actionContext.Response = response;
}
关于asp.net - Web Api - 如何直接从 OnActionExecuting 过滤器停止 Web 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822365/