【问题标题】:Why is my ExceptionFilter not fetching exceptions when the site is deployed?为什么我的 ExceptionFilter 在部署站点时没有获取异常?
【发布时间】:2014-03-11 11:05:56
【问题描述】:

我有一个 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 标签:

&lt;customErrors mode="Off"&gt;&lt;/customErrors&gt;

但不幸的是,这并没有奏效。所以我的问题是:我该怎么做才能显示我自己的错误消息?

【问题讨论】:

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


    【解决方案1】:

    我发现我的过滤器正在捕获异常并且“真正的”问题是 IIS 7。默认情况下,当 Http StatusCode > 400 时,IIS 7 使用它自己的(自定义)错误页面。所以在我的情况下,使用 IIS 7它是自己的错误页面。显然这不是我想要的。

    解决这个问题的两种方法是:

    1. 设置Response.TrySkipIisCustomErrors = true;。这将告诉 IIS7 不要使用它自己的错误页面,而是使用ResponseText
    2. web.config 元素的system.webServer 元素中添加以下行:&lt;httpErrors existingResponse="PassThrough"&gt;&lt;/httpErrors&gt;

    有关此主题的更多信息,请参阅What to expect from IIS7 custom error module

    【讨论】:

      【解决方案2】:

      如果你只想显示Error occurred那么你可以试试这个

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

      上面的代码将重定向到您在defaultredirect中提到的页面

      【讨论】:

      • 谢谢,但我只对文本感兴趣。我不想要重定向。我尝试将模式设置为RemoteOnly,但没有任何区别。
      猜你喜欢
      • 2010-11-16
      • 2012-01-22
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 2020-11-16
      • 2010-11-25
      相关资源
      最近更新 更多