willem
willem

Reputation: 27027

Is there a way to check, programmatically, if an ASP.NET application's CustomErrors are set to Off?

We usually catch unhandled exceptions in Global.asax, and then we redirect to a nice friendly error page. This is fine for the Live environment, but in our development environment we would like to check if CustomErrors are Off, and if so, just throw the ugly error.

Is there an easy way to check if CustomErrors are Off through code?

Upvotes: 25

Views: 3786

Answers (3)

kaptan
kaptan

Reputation: 3149

I would suggest using the following property:

HttpContext.Current.IsCustomErrorEnabled

As mentioned here, IsCustomErrorEnabled takes more things like RemoteOnly into consideration:

The IsCustomErrorEnabled property combines three values to tell you whether custom errors are enabled for a particular request. This isn't as simple as reading the web.config file to check the section. There's a bit more going on behind the scenes to truly determine whether custom errors are enabled.

The property looks at these three values:

  1. The web.config's < deployment > section's retail property. This is a useful property to set when deploying your application to a production server. This overrides any other settings for custom errors.

  2. The web.config's < customErrors > section's mode property. This setting indicates whether custom errors are enabled at all, and if so whether they are enabled only for remote requests.

  3. The HttpRequest object's IsLocal property. If custom errors are enabled only for remote requests, you need to know whether the request is from a remote computer.

Upvotes: 36

Jemes
Jemes

Reputation: 2842

This should do the trick...

using System.Web.Configuration;
using System.Configuration;

// pass application virtual directory name
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/TestWebsite");
CustomErrorsSection section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
CustomErrorsMode mode=section.Mode;

Upvotes: 1

djdd87
djdd87

Reputation: 68476

Yep, the through WebConfigurationManager:

System.Configuration.Configuration configuration =
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");

System.Web.Configuration.CustomErrorsSection section =
    (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

Once you have the section, you can check whether the mode is on or off as follows:

CustomErrorsMode mode = section.Mode;
if (mode == CustomErrorsMode.Off)
{
    // Do something
}

Upvotes: 13

Related Questions