HasanG
HasanG

Reputation: 13161

How to redirect to pre-defined error page?

I have error page settings in my web.config like:

<customErrors mode="RemoteOnly" defaultRedirect="ErrorDocs/500.htm">
    <error statusCode="404" redirect="ErrorDocs/404.htm"/>
    <error statusCode="403" redirect="ErrorDocs/403.htm"/>
</customErrors>

Is there a simple way to redirect to 404 page without typing its name? Ex: Response.Redirect(404 status coded page); Or is there a way to get default 404 location?

Upvotes: 0

Views: 994

Answers (3)

aronchick
aronchick

Reputation: 7128

Well you can certainly get the settings out of your web.config file programmatically if you want - http://msdn.microsoft.com/en-us/library/system.configuration.configurationsectiongroup.aspx - rough code:

    string my404Setting;

    // Get the application configuration file.
    System.Configuration.Configuration config =
        ConfigurationManager.OpenExeConfiguration(
        ConfigurationUserLevel.None);

    foreach (ConfigurationSectionGroup sectionGroup in config.SectionGroups)
    {
        if (sectionGroup.type == "customErrors" )
        {
            foreach (ConfigurationSections section in sectionGroup.Sections)
            {
               if (section.StatusCode = "404")
               {
                  my404Setting = section.Redirect;
                  break;
               }
            }
            break; 
        }
    }
}

Uglier than it should be, but that's how you'd read what you want.

Upvotes: 2

mga911
mga911

Reputation: 1546

From answer here: Best way to implement a 404 in ASP.NET

protected void Application_Error(object sender, EventArgs e){
  // An error has occured on a .Net page.
  var serverError = Server.GetLastError() as HttpException;

  if (null != serverError){
    int errorCode = serverError.GetHttpCode();

    if (404 == errorCode){
      Server.ClearError();
      Server.Transfer("/Errors/404.htm");
    }
  }
}

Upvotes: 1

ddc0660
ddc0660

Reputation: 4052

No, unfortunately those paths only work with static page paths.

Upvotes: 0

Related Questions