本文介绍了如何使用动作过滤器在 asp.net mvc 中集中模型状态验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在几个地方写了这段代码并且总是重复这个逻辑:
I write this code in several places and always repeat this logic:
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
?
Is there any way using action filters, not to be repeating the try-catch
, ask if the model is valid and return Json(false)
as ActionResult
?
推荐答案
为了符合 REST,你应该返回 http bad request 400 表示请求格式错误(模型无效)而不是返回 Json(false)
.
To conform with REST, you should return http bad request 400 to indicate that the request is malformed (model is invalid) instead of returning Json(false)
.
从 asp.net 官方网站 用于 web api:
Try this attribute from asp.net official site for web api:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
asp.net mvc 的版本可能是这样的:
A version for asp.net mvc could be like this:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.Controller.ViewData.ModelState.IsValid)
{
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
}
这篇关于如何使用动作过滤器在 asp.net mvc 中集中模型状态验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!