具有异常参数的ModelState.AddModelError的用途

Dav*_*ner 6 asp.net-mvc-2

是否有一个AddModelError()的重载用于将Exception作为参数?

如果我在控制器中包含以下代码:

ModelState.AddModelError( "", new Exception("blah blah blah") );
ModelState.AddModelError( "", "Something has went wrong" );

if (!ModelState.IsValid)
    return View( model );
Run Code Online (Sandbox Code Playgroud)

以下是我的观点:

<%= Html.ValidationSummary( "Please correct the errors and try again.") %>
Run Code Online (Sandbox Code Playgroud)

然后,错误摘要中仅显示"Something出错"文本.

Bui*_*ted 3

检查源 ModelError 接受两者,并且用途用于模型类型转换失败。

在这种特殊情况下,需要在必要时沿着异常树向下获取内部异常,以找到实际的根错误,而不是通用的顶级异常消息。

foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList()) {
    for (Exception exception = error.Exception; exception != null; exception = exception.InnerException) {
        if (exception is FormatException) {
            string displayName = propertyMetadata.GetDisplayName();
            string errorMessageTemplate = GetValueInvalidResource(controllerContext);
            string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);
            modelState.Errors.Remove(error);
            modelState.Errors.Add(errorMessage);
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它循环遍历 ModelError 中的异常以查找 FormatException。这是我在 MVC 2 和 MVC 3 中能找到的唯一真正的参考。

也就是说,对于常规使用来说可能没有必要。