我在几个地方写这个代码,总是重复这个逻辑:
public ActionResult MyMethod(MyModel collection) { if (!ModelState.IsValid) { return Json(false);//to read it from javascript,it's always equal } else { try { //logic here return Json(true);//or Json(false); } catch { return Json(false);//to read it from javascript,it's always equal } } }
有没有办法使用动作过滤器,不要重复try-catch,询问模型是否有效并返回Json(false)作为ActionResult?
解决方法
为了符合REST,您应该返回http错误请求400以指示请求格式错误(模型无效),而不是返回Json(false).
尝试这个属性从asp.net official site为web api:
public class ValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ModelState.IsValid == false) { actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest,actionContext.ModelState); } } }
asp.net mvc的版本可能是这样的:
public class ValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.Controller.ViewData.ModelState.IsValid == false) { filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }