为什么我的ExceptionFilter在部署站点时没有获取异常?

时间:2014-03-11 11:05:57

标签: c# asp.net-mvc asp.net-mvc-4

我有一个MVC 4应用程序,并且我已经注册了一个异常过滤器:

的Global.asax.cs:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    // Here my filter gets registered
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

FilterConfig.cs:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleUnhandledExceptionFilter());
    }
}

HandleUnhandledExceptionFilter.cs:

public class HandleUnhandledExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.HttpContext.Response.StatusCode = 500;
        filterContext.HttpContext.Response.Write("An unknown error occured");
        filterContext.ExceptionHandled = true;
    }
}

注意,我使用WEB API框架,但我使用的是MVC过滤器。

发生异常时,我想显示文本An unknown error occured。我在本地执行网站时工作正常。当我发布网站时,将发布的文件复制到网络服务器并浏览我的机器(不是网络服务器)并获得一个结果,我看不到文本An unknown error occured。相反,我得到了错误页面的来源。所以我从字面上看这个:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html .... etc.

首先我想也许它与customErrors有关,所以我在我的webconfig中添加了customErrors标记:

<customErrors mode="Off"></customErrors>

但不幸的是,这并没有成功。所以我的问题是:我需要做些什么才能显示自己的错误消息?

2 个答案:

答案 0 :(得分:2)

我发现我的过滤器正在捕捉异常并且真正的&#39;问题是IIS 7.默认情况下,当Http StatusCode&gt;时,IIS 7使用它自己的(自定义)错误页面。因此,在我的情况下,IIS 7使用了它自己的错误页面。显然这不是我想要的。

解决此问题的两种方法是:

  1. 设置Response.TrySkipIisCustomErrors = true;。这将使IIS7不使用它自己的错误页面,而是使用ResponseText
  2. web.config元素的system.webServer中添加以下行:<httpErrors existingResponse="PassThrough"></httpErrors>
  3. 有关此主题的更多信息,请参阅What to expect from IIS7 custom error module

答案 1 :(得分:0)

如果您只是想显示Error occurred,那么您可以试试这个

 <customErrors mode="RemoteOnly" defaultRedirect="/YOURCONTROLLER/VIEW" />

上面的代码会重定向到您在defaultredirect

中提到的页面
相关问题