【发布时间】:2011-11-25 14:07:13
【问题描述】:
我正在尝试获取对 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/ 的内容。
【问题讨论】:
-
这可能是一个愚蠢的问题,但该部分是否存在于您的配置文件中?
-
合法且可以帮助他人。不要删除它。
-
谢谢!我傻眼了,因为获取 customError 部分与获取自定义部分不同。我想它会是一样的。
标签: c# asp.net web-config custom-errors