【问题标题】:get reference to the ASP.NET web.config customErrors section获取对 ASP.NET web.config customErrors 部分的引用
【发布时间】: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


【解决方案1】:

试试这个:

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

// Get the section.
CustomErrorsSection customErrors =
    (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

这里有更多关于这个主题的信息:CustomError Class

【讨论】:

  • 谢谢!我花了一段时间搜索这个,然后我在发布后立即返回 Microsoft 页面,我发现我在前几次点击页面时没有向下滚动足够远。有时,您在寻找答案时感到非常沮丧,以至于您无法清楚地思考以解释您正在搜索的材料。
  • 我会将您的答案标记为正确答案,但您的代码 sn-p 仅显示您链接到的解决方案的一部分。您没有粘贴声明配置来源的部分。
  • 配置 = WebConfigurationManager.OpenWebConfiguration("~/Web.config");自定义错误部分
  • @Darren 感谢您添加缺失的部分! :) 更新了答案。
猜你喜欢
  • 2013-12-21
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 2010-10-11
相关资源
最近更新 更多