我有一个预先操作的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; }