如何重定向到预定义的错误页面?

问题描述:

我有错误页面设置在我的web.config这样的:如何重定向到预定义的错误页面?

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

有没有一种简单的方法来重定向到404页,而无需键入它的名字?例如:Response.Redirect(404状态代码页); 或者有没有办法获得默认的404位置?

那么你可以肯定得到的设置你的web.config文件的程序,如果你想 - http://msdn.microsoft.com/en-us/library/system.configuration.configurationsectiongroup.aspx - 粗代码:

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; 
     } 
    } 
} 

丑陋比它应该是,但这就是你如何阅读你想要的。

+0

虽然我已经实现了另一种处理错误的方法,但这是最接近的答案。 – 2010-07-23 17:08:28

不,不幸的是,这些路径只适用于静态页面路径。

从这里回答: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"); 
    } 
    } 
}