以编程方式检查httpErrors errorMode

Jak*_*ade 9 c# asp.net iis-7 web-config

如何获取<system.webServer><httpErrors>web.config 中元素中设置的errorMode属性的值?

我正在尝试在ASP.NET Web应用程序中实现一些"自我诊断".当应用程序启动时,它会运行web.config中的某些设置并确认它们已正确设置.

虽然在<system.web><customErrors>元素中设置了errormode时这段代码工作得很好,

var errSec = (CustomErrorsSection)HttpContext.Current.GetSection("system.web/customErrors");
Response.Write(errSec.Mode.ToString());
Run Code Online (Sandbox Code Playgroud)

一旦在IIS7上部署站点并且现在找到此设置,它将无法工作system.webServer -> httpErrors.

这不起作用:

var errSec = (CustomErrorsSection)HttpContext.Current.GetSection("system.webServer/httpErrors");
Run Code Online (Sandbox Code Playgroud)

而铸造到一个CustomErrorsSection也似乎是一个坏主意,必须有一个更好的类型使用?

我在IIS.NET,HTTP错误 上发现了这篇文章,但我希望这样做而不依赖于Microsoft.Web.Administration库.

有什么建议??

UPDATE

好的,根据下面的建议,我试过这个:

var errSec = (ConfigurationSection)HttpContext.Current.GetSection("system.webServer/httpErrors");
Response.Write(errSec.SectionInformation.GetRawXml().ToString());
Run Code Online (Sandbox Code Playgroud)

但这也不起作用,该errSec对象为null.另外,如果我<system.web><customErrors>使用相同的方法加载该部分,则GetRawXml()方法调用将失败并显示"此操作在运行时不适用".异常消息.

我知道如何将整个web.config作为xml文件加载并查询以获取我需要的元素.但在我看来,似乎必须有一个更优雅的方法.

如何将web.config读取为xml:

var conf = XDocument.Load(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "web.config");
var errMode = conf.Root.Element("system.webServer").Element("httpErrors").Attribute("errorMode").Value;
Run Code Online (Sandbox Code Playgroud)

......但这只是令人讨厌的!如果在machine.config或类似设置中设置了errorMode设置,它将无法工作.

Vin*_*ayC 1

(CustomErrorsSection)HttpContext.Current.GetSection("system.webServer/httpErrors")将不起作用,因为该部分来自 IIS7 配置架构,与 CustomErrorsSection(来自 ASP.NET 配置)不同。如果您不想依赖 IIS7 程序集(您不应该这样做),唯一的方法是使用ConfigurationSection对象通过其子元素进行枚举并获得您想要的。或者您可以直接选取配置文件,将其视为 XML 并读取必要的值。