我正在尝试获取对 web.config customErrors 部分的引用。当我使用以下代码时,我总是得到一个空值。当我获得对我创建的自定义部分的引用时,我没有这个问题,所以我有点傻眼,为什么这不起作用。
CustomErrorsSection customErrorSection =
ConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
我也试过这个:
CustomErrorsSection customErrorSection =
WebConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
我也试过这个:
CustomErrorsSection customErrorSection =
WebConfigurationManager.GetWebApplicationSection("customErrors") as CustomErrorSection;
编辑:
啊!大多数事情都是这种情况,我在问完问题后马上就找到了答案。
这对我有用:
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/");
CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
或者更简单地像这样:
CustomErrorsSection customErrors = (CustomErrorsSection) WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
这也有效:
CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
所以我想我现在明白为什么我首先会遇到这个问题。我错误地认为我可以通过尝试 GetSection("customErrors") 来获得对 customErrors 部分的引用,但我没有告诉它它所在的根部分,我的尝试是基于我知道如何当我没有意识到我的自定义部分是该部分的根时,获取一个自定义部分,因此当我调用 GetSection() 时,我不必在它前面添加类似 system.Web/ 的内容。