获取对ASP.NET web.config customErrors部分的引用

Fra*_*ale 4 c# asp.net web-config custom-errors

我正在尝试获取对web.config customErrors部分的引用.当我使用以下代码时,我总是得到一个null.当我得到一个我创建的自定义部分的引用时,我没有这个问题,所以我有点傻眼为什么这不起作用.

CustomErrorsSection customErrorSection =
    ConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
Run Code Online (Sandbox Code Playgroud)

我也试过这个:

CustomErrorsSection customErrorSection = 
    WebConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
Run Code Online (Sandbox Code Playgroud)

我也试过这个:

CustomErrorsSection customErrorSection =
    WebConfigurationManager.GetWebApplicationSection("customErrors") as CustomErrorSection;
Run Code Online (Sandbox Code Playgroud)

编辑:

哎呀!大多数情况都是如此,我在问到这个问题之后就找到了答案.

这对我有用:

System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/");
CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
Run Code Online (Sandbox Code Playgroud)

或者更简单地这样:

CustomErrorsSection customErrors = (CustomErrorsSection) WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
Run Code Online (Sandbox Code Playgroud)

这也有效:

CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
Run Code Online (Sandbox Code Playgroud)

所以我想我现在明白了为什么我首先遇到了这个问题.我错误地认为我可以通过尝试GetSection("customErrors")来获取对customErrors部分的引用,但是我没有告诉它它所居住的根部分,并且我的基础是我的尝试基于我知道如何当我没有意识到我的自定义部分是该部分的根时,得到一个自定义部分,所以当我调用GetSection()时,我不必在它前面添加类似system.Web /的东西.

Len*_*rri 8

试试这个:

var configuration = WebConfigurationManager.OpenWebConfiguration("~/Web.config");

// Get the section.
CustomErrorsSection customErrors =
    (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
Run Code Online (Sandbox Code Playgroud)

有关此主题的更多信息:CustomError类

  • 我会将您的答案标记为正确答案,但您的代码段仅显示您链接到的解决方案的一部分.您没有粘贴声明配置来源的部分. (2认同)