2013-03-28 38 views
1

我想在應用程序拋出異常但重定向到該頁面時重定向到錯誤頁面。這裏是我的代碼:Response.Redirect在Global.asax中不起作用

protected void Application_Error(object sender, EventArgs e) 
    { 

     StringBuilder theBody = new StringBuilder(); 

     Exception exception = Server.GetLastError(); 

     StackTrace st = new StackTrace(exception, true); 
     // Get the top stack frame 
     StackFrame frame = st.GetFrame(0); 
     // Get the line number from the stack frame 
     int line = frame.GetFileLineNumber(); 

     string file = frame.GetFileName(); 

     MethodBase site = exception.TargetSite; 
     string methodName = site == null ? null : site.Name; 

     string type = exception.GetType().ToString(); 

     theBody.Append("Line: " + line + "<br/>"); 
     theBody.Append("Method: " + methodName + "<br/>"); 
     theBody.Append("File: " + methodName + "<br/>"); 
     theBody.Append("IP: " + Request.ServerVariables["REMOTE_HOST"] + "<br/>"); 
     theBody.Append("Error Message: " + exception.Message + "<br/>"); 
     theBody.Append("Error Stack:" + exception.StackTrace); 

      Response.Redirect("~/404.aspx", false); 
      Context.ApplicationInstance.CompleteRequest(); 


     ... 
    } 

我嘗試這樣的測試頁

try 
     { 

      throw new Exception("Test exception!!"); 
     } 
     catch (Exception) 
     { 


     } 

它doen't重定向404.aspx保持停留測試頁上。我應該怎麼做重定向404.aspx?

+4

你爲什麼不使用默認的asp.net錯誤頁面的功能解釋呢? http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/displaying-a-custom-error-page-cs – 2013-03-28 10:26:18

+0

另外 - 爲什麼你準備一個你永遠不會發送的電子郵件? – 2013-03-28 10:27:34

+0

@Hainesy我沒有顯示,因爲你可以看到「...」有一個電子郵件發送代碼。但是,謝謝你的建議。我只是用我的重定向代碼來顯示這裏的人。 – cagin 2013-03-28 10:30:14

回答

1

一套它在web.config中在這個環節http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/displaying-a-custom-error-page-cs

<system.web> 
     <customErrors mode="On" 
         defaultRedirect="~/ErrorPages/Oops.aspx" /> 

     ... 
    </system.web> 
+0

我做了這一個但結果相同。 TestPage不重定向。 – cagin 2013-03-28 11:30:28

+0

刪除try&catch塊..只是添加拋出新的異常(「測試異常!!」);它將被重定向到404.aspx。因爲當你在try和catch塊中添加任何異常時,你將會在同一頁面上,但是如果你刪除了try&catch塊,它將轉到Global.asax中的ApplicationError函數然後到在web.config上設置的默認重定向頁面。希望這會幫助你 – 2013-03-28 11:36:26

+0

是的,我刪除了try catch塊,它運行。但是,我需要刪除我的web項目中的所有try-catch塊嗎?如果是的話,它安全嗎? – cagin 2013-03-28 11:44:53

相關問題