代码之家  ›  专栏  ›  技术社区  ›  willem

如果ASP.NET应用程序的customErrors设置为off,是否有一种方法可以通过编程方式检查?

  •  22
  • willem  · 技术社区  · 14 年前

    我们通常在global.asax中捕获未处理的异常,然后重定向到一个友好的错误页。这对于实际环境是很好的,但是在我们的开发环境中,我们想检查客户错误是否关闭,如果关闭了,只需抛出一个丑陋的错误。

    有没有一种简单的方法可以通过代码检查客户错误是否已关闭?

    3 回复  |  直到 8 年前
        1
  •  12
  •   djdd87    14 年前

    是的,直通车 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
  •  35
  •   kaptan    12 年前

    我建议使用以下属性:

    HttpContext.Current.IsCustomErrorEnabled
    

    如上所述 here ,IsCustomerRorEnabled考虑了更多的事情,如RemoteOnly:

    isCustomerRorEnabled属性结合三个值告诉您 是否为特定请求启用自定义错误。这不是 只需读取web.config文件检查 部分。在幕后还有更多的事情要做 确定是否启用自定义错误。

    属性查看以下三个值:

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

    2. web.config的<客户错误>部分的模式属性。此设置 指示是否启用自定义错误,如果启用,则是否 它们仅对远程请求启用。

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

        3
  •  1
  •   Jemes    14 年前

    这应该会起作用…

    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;