【发布时间】:2015-10-06 07:00:40
【问题描述】:
我有一个 ASP.NET MVC Web 应用程序,我正在尝试改进它的错误处理能力。我阅读了 HandleErrorAttribute 基类,并希望将它与我的控制器类一起使用。但是,当我从使用该属性装饰的控制器类中的一个方法中抛出测试异常时,我的派生类中的 OnException 覆盖不会触发。我没有触发我派生的错误处理类的 OnException 方法,而是看到一条 XML 格式的通用错误消息,并且该通用错误消息在我的应用程序的任何地方都找不到:
<Error>
<Message>An error has occurred.</Message>
</Error>
我做错了什么?
注意我尝试将以下自定义错误元素添加到我的 web.config 文件中的 system.web 元素中,如这篇 SO 帖子所示,但 没有帮助:
ASP.net MVC [HandleError] not catching exceptions
<customErrors mode="On" defaultRedirect="Error" />
这是我的 HandleErrorAttribute 派生类:
public class HandleControllerErrors : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
// Breakpoint set here never hit.
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");
filterContext.Result = new ViewResult()
{
// Use the ErrorInController view.
ViewName = "ErrorInController",
ViewData = new ViewDataDictionary(model)
};
}
}
这是我如何装饰我的控制器类。我有一个方法在 try/catch 块内强行抛出一个 not 异常。:
[HandleControllerErrors]
public class ValuesController : ApiController
{
[Route("Api/TestException/")]
public IHttpActionResult TestException()
{
throw new InvalidCastException("Fake invalid cast exception.");
}
}
【问题讨论】:
-
那么是 MVC 还是 Web API 应用程序?或两者?即使两者都有,是哪一部分?
标签: c# asp.net-web-api custom-attributes handleerror