views:

28

answers:

3

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?

A: 

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

ddc0660
+1  A: 

From answer here: http://stackoverflow.com/questions/667053/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");
    }
  }
}
mga911
+1  A: 

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.

aronchick
Although I've implemented another way to handle errors this is the nearest answer.
HasanGursoy