How do I get the value of the errorMode property set in the <system.webServer><httpErrors>
element in web.config?
I'm trying to implement some "self-diagnostics" in an ASP.NET web application. When the app starts, it runs through some of the settings in web.config and confirm they're set correctly.
While this code works quite nicely when the errormode is set in the <system.web><customErrors>
element,
var errSec = (CustomErrorsSection)HttpContext.Current.GetSection("system.web/customErrors");
Response.Write(errSec.Mode.ToString());
it won't work once the site is deployed on IIS7 and this setting is now found in system.webServer -> httpErrors
.
This won't work:
var errSec = (CustomErrorsSection)HttpContext.Current.GetSection("system.webServer/httpErrors");
And casting to a CustomErrorsSection
also seems like a bad idea, there must be a better type to use?
I found this article on IIS.NET, HTTP Errors , but I hope to do this without the dependency on the Microsoft.Web.Administration library.
Any suggestions??
UPDATE
Okay, based on the suggestion below, I tried this:
var errSec = (ConfigurationSection)HttpContext.Current.GetSection("system.webServer/httpErrors");
Response.Write(errSec.SectionInformation.GetRawXml().ToString());
But that doesn't work either, the errSec
object is null. And on a side-note, if I load the <system.web><customErrors>
section using the same approach, the GetRawXml()
method call fails with a "This operation does not apply at runtime." exception message.
I know how to load the whole web.config as an xml file and query that to get to the element I need. But it just seems to me like there must be a more elegant approach.
How to read web.config as xml:
var conf = XDocument.Load(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "web.config");
var errMode = conf.Root.Element("system.webServer").Element("httpErrors").Attribute("errorMode").Value;
... but that's just nasty! And if the errorMode setting is set in machine.config or similar, it won't work.