从ASP.NET MVC 3默认模型Binder for Action方法参数强制UpdateModel行为

时间:2012-01-25 19:56:35

标签: asp.net-mvc-3 validation model-binding

我正在ASP.Net MVC 3应用程序中实现错误处理策略。我编写了一个实现IExceptionFilter等的属性。这个函数正常运行,处理异常抛出action方法并返回序列化为JSON的异常信息。

我想使用此属性来处理模型绑定器在将数据传递给Action方法时发现的验证错误。例如,如果我将一个对象POST一个动作方法,该方法被反序列化为Action Method参数,我希望它在UpdateModel发生验证错误时抛出异常。现在,默认的模型绑定器似乎表现得像TryUpdateModel,只是翻转ModelState.IsValid而不是抛出异常。

[ActionExceptionJsonHandler]
public ActionResult CreateSomething(SomethingViewData account)
{
// If model binding fails validation an exception should be thrown and no code is executed here
// Do stuff here
}

如果默认模型绑定器以与UpdateModel相同的方式抛出异常,那么IExceptionFilter将捕获它并处理将验证错误返回给客户端。没有它,开发人员必须编写代码来检查ModelState等。

所以底线我有两个相关的问题:

  1. 有没有办法让默认模型绑定器在验证失败时抛出异常?
  2. 有关使用此方法与在每个操作方法中手动检查ModelState的任何想法吗?
  3. 感谢。

1 个答案:

答案 0 :(得分:0)

我的解决方案最终是实现ActionFilterAttribute,如下所示。在OnActionExecuting中我检查ModelState.IsValid,如果它是false我将模型状态错误序列化为JSON并设置Result对象有效地取消执行。这允许我返回包含模型绑定错误的自定义JSON序列化对象。

    public override void OnActionExecuting(ActionExecutingContext filterContext) {

        if (filterContext.Controller.ViewData.ModelState.IsValid) {
            base.OnActionExecuting(filterContext);
            return;
        }

        var returnDto = new ReturnDto
                            {
                                Success = false,
                                Errors = Tools.GetModelStateErrors(filterContext.Controller.ViewData.ModelState)
                            };

        // AllowGet is fine provided we are not returning a javascript array
        filterContext.Result = new JsonResult { Data = returnDto, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }