【问题标题】:Exception not being handled by ErrorHanldeAttribute or OnException method in ASP.NET MVC 5ASP.NET MVC 5 中的 ErrorHanldeAttribute 或 OnException 方法未处理异常
【发布时间】:2016-10-15 06:17:18
【问题描述】:

我正在尝试实现一种全局异常处理技术,以避免在我的控制器的每个操作上使用 try/catch 块,但我的应用程序在覆盖的 OnException 方法或 ErrorHandleAttribute 到达之前崩溃。

这是一个简化的测试代码:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Test()
    {
        throw new Exception("Exception Test");
    }

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null || filterContext.ExceptionHandled)
        {
            return;
        }

        var message = filterContext.Exception.Message;
        filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
        filterContext.ExceptionHandled = true;
    }
}

在 Web.Config 中:

<system.web>
    <customErrors mode="On" defaultRedirect="Error"/>

如果我在“throw”行设置断点并尝试访问 /Home/Test,我的应用程序将崩溃,并且只有在此之后才会到达 OnException 方法和 HandleErrorAttribute。

我错过了什么吗?

谢谢。

【问题讨论】:

  • @NightOwl888 好文章!我尝试实现那里描述的最后四种方法(因为前两种是我最初拥有的方法)但我没有成功。我的应用程序将在它们中的任何一个被触发之前崩溃。

标签: asp.net asp.net-mvc exception error-handling exception-handling


【解决方案1】:

您需要注册HandleError 过滤器。

filters.Add(new HandleErrorAttribute{View = "Error"});

【讨论】:

  • 它没有用。我将该行放在 App_Start/FilterConfig.cs 中,并使用 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters) 在 Global.asax 中注册;但我的应用程序仍然崩溃。
猜你喜欢
  • 1970-01-01
  • 2010-10-11
  • 2012-08-25
  • 2012-09-17
  • 2012-02-02
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多