【问题标题】:Is there a way to check, programmatically, if an ASP.NET application's CustomErrors are set to Off?有没有办法以编程方式检查 ASP.NET 应用程序的 CustomErrors 是否设置为 Off?
【发布时间】:2011-03-31 14:09:35
【问题描述】:

我们通常在 Global.asax 中捕获未处理的异常,然后我们重定向到一个友好的错误页面。这对于 Live 环境很好,但在我们的开发环境中,我们想检查 CustomErrors 是否为 Off,如果是,则抛出丑陋的错误。

有没有一种简单的方法可以通过代码检查 CustomErrors 是否关闭?

【问题讨论】:

标签: asp.net


【解决方案1】:

是的,通过WebConfigurationManager

System.Configuration.Configuration configuration =
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");

System.Web.Configuration.CustomErrorsSection section =
    (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

拥有该部分后,您可以按如下方式检查模式是打开还是关闭:

CustomErrorsMode mode = section.Mode;
if (mode == CustomErrorsMode.Off)
{
    // Do something
}

【讨论】:

    【解决方案2】:

    这应该可以解决问题...

    using System.Web.Configuration;
    using System.Configuration;
    
    // pass application virtual directory name
    Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/TestWebsite");
    CustomErrorsSection section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
    CustomErrorsMode mode=section.Mode;
    

    【讨论】:

      【解决方案3】:

      我建议使用以下属性:

      HttpContext.Current.IsCustomErrorEnabled
      

      here 所述,IsCustomErrorEnabled 考虑了更多类似 RemoteOnly 的内容:

      IsCustomErrorEnabled 属性结合了三个值来告诉你 是否为特定请求启用自定义错误。这不是 就像阅读 web.config 文件来检查 部分。真正的幕后还有更多的事情发生 确定是否启用自定义错误。

      该属性查看这三个值:

      1. web.config 的 部分的零售属性。这是一个 将应用程序部署到生产环境时设置的有用属性 服务器。这会覆盖自定义错误的任何其他设置。

      2. web.config 的 部分的模式属性。这个设置 指示是否完全启用自定义错误,如果启用,是否 它们仅对远程请求启用。

      3. HttpRequest 对象的 IsLocal 属性。如果仅为远程启用自定义错误 请求,您需要知道请求是否来自远程 电脑。

      【讨论】:

        猜你喜欢
        • 2010-09-14
        • 1970-01-01
        • 2015-12-19
        • 2010-10-30
        • 2021-12-21
        • 2011-07-03
        • 1970-01-01
        • 2016-05-30
        • 2014-07-24
        相关资源
        最近更新 更多