views:

98

answers:

1

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.

+1  A: 

(CustomErrorsSection)HttpContext.Current.GetSection("system.webServer/httpErrors") will not work because that section is from IIS7 configuration schema and not same as CustomErrorsSection (from ASP.NET configuration). If you don't want to take dependency on IIS7 assembly (which you shouldn't), only way is to use ConfigurationSection object to enumerate via its children elements and get want you want. Or you can directly pick up config file, treat it as an XML and read the necessary values.

VinayC
You can always use reflection ;-)
Steven
Yeah, I forgot to mention the "read as xml" approach as another option I'd like to avoid. :) I was trying to load it as a ConfigurationSection, but I couldn't figure out how to get to the errorMode property. Any ideas?
Jakob Gade