Asp.net
Web Api - 如何直接從 OnActionExecuting 過濾器停止 Web 管道
我有一個預操作 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); } }
設置 Response.Result。如果結果不為空,則不會執行該操作。確切的語法現在正在逃避我,但它很簡單
if(actionContext.ModelState.IsValid == false) { var response = actionContext.Request.CreateErrorResponse(...); actionContext.Response = response; }
你真的看過 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