2011-10-11 91 views
1

我在本地使用Asp.net 4 C#和IIS 7,並在生產服務器上使用IIS 7.5。在IIS 7.5和IIS 7上顯示自定義錯誤頁面

我需要顯示自定義錯誤頁面。目前,我在Global.asax中使用了一些邏輯來繞過IIS默認頁面。 本地使用IIS 7我能夠成功顯示CustomPages,但在生產(IIS 7.5)服務器默認情況下IIS頁面仍然存在。 我使用Response.TrySkipIisCustomErrors = true;,但在生產服務器上不起作用。

你能指出我解決這個問題的方法嗎?

我的代碼在Global.Asax

Application_Error 

Response.TrySkipIisCustomErrors = true; 
       if (ex is HttpException) 
       { 
        if (((HttpException)(ex)).GetHttpCode() == 404) 
        { 

         Server.Transfer("~/ErrorPages/404.aspx"); 
        } 
       } 
       // Code that runs when an unhandled error occurs. 
       Server.Transfer("~/ErrorPages/Error.aspx"); 
+0

感謝您的編輯 – GibboK

+0

只是出於好奇,爲什麼你不只是讓你的web.config處理自定義錯誤?必要時登錄application_error並讓配置處理下一個。更容易打開/關閉,配置等。 –

+0

亞當我做服務器轉移得到404。顯示時出現的Asp.net自定義錯誤顯示302默認情況下重定向 – GibboK

回答

2

我做了這是一個模塊,而不是在Global.asax並迷上它爲標準自定義錯誤的東西的方式。試試這個:

public class PageNotFoundModule : IHttpModule 
{ 
    public void Dispose() {} 

    public void Init(HttpApplication context) 
    { 
     context.Error += new EventHandler(context_Error); 
    } 

    private void context_Error(object sender, EventArgs e) 
    { 
     var context = HttpContext.Current; 

     // Only handle 404 errors 
     var error = context.Server.GetLastError() as HttpException; 
     if (error.GetHttpCode() == 404) 
     { 
      //We can still use the web.config custom errors information to decide whether to redirect 
      var config = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"); 

      if (config.Mode == CustomErrorsMode.On || (config.Mode == CustomErrorsMode.RemoteOnly && context.Request.Url.Host != "localhost")) 
      { 
       //Set the response status code 
       context.Response.StatusCode = 404; 

       //Tell IIS 7 not to hijack the response (see http://www.west-wind.com/weblog/posts/745738.aspx) 
       context.Response.TrySkipIisCustomErrors = true; 

       //Clear the error otherwise it'll get handled as usual 
       context.Server.ClearError(); 

       //Transfer (not redirect) to the 404 error page from the web.config 
       if (config.Errors["404"] != null) 
       { 
        HttpContext.Current.Server.Transfer(config.Errors["404"].Redirect); 
       } 
       else 
       { 
        HttpContext.Current.Server.Transfer(config.DefaultRedirect); 
       } 
      } 
     } 
    } 
} 
+0

我在嘗試,你可以發佈你的Web.Config的例子嗎?謝謝 – GibboK

+0