Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get reference to the ASP.NET web.config customErrors section

I'm trying to obtain a reference to the web.config customErrors section. When I use the following code I always get a null. I don't have this problem when I get a reference to a custom section that I've created so I'm a bit dumbfounded why this won't work.

CustomErrorsSection customErrorSection =
    ConfigurationManager.GetSection("customErrors") as CustomErrorsSection;

I've also tried this:

CustomErrorsSection customErrorSection = 
    WebConfigurationManager.GetSection("customErrors") as CustomErrorsSection;

I've also tried this:

CustomErrorsSection customErrorSection =
    WebConfigurationManager.GetWebApplicationSection("customErrors") as CustomErrorSection;

EDIT:

ARGH! Such is the case with most things I figured out the answer right after asking the question.

This works for me:

System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/");
CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

Or more simply like this:

CustomErrorsSection customErrors = (CustomErrorsSection) WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");

This also works:

CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;

So I guess I understand now why I had the problem in the first place. I had incorrectly thought that I could get a reference to the customErrors section by trying to GetSection("customErrors") but I had failed to tell it what root section it lived in and I was basing my attempts on the fact that I knew how to get a custom section when I failed to realize that my custom section was the root of the section so I did not have to prepend something like system.Web/ in front of it when I called GetSection().

like image 735
Frank Hale Avatar asked Feb 23 '23 07:02

Frank Hale


1 Answers

Try this:

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

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

More on the subject here: CustomError Class

like image 177
Leniel Maccaferri Avatar answered Mar 25 '23 07:03

Leniel Maccaferri