2012-12-12 91 views
1

我在asp.net中有web應用程序。 我必須實現自定義錯誤頁面。 意味着發生任何錯誤(運行時)。 我必須顯示errorpage.aspx 上的異常和堆棧跟蹤,我應該從母版頁還是頁級處理以及如何處理。asp.net中的自定義錯誤頁面

<customErrors mode="On" defaultRedirect="~/Error_Page.aspx"></customErrors> 
+1

如果您設置自定義錯誤關閉它只會顯示你在ASP默認異常頁面錯誤和堆棧跟蹤。不知道這是否會爲你做? – middelpat

+0

我必須寫詳細信息和關於ErrorPage.aspx上的錯誤的堆棧跟蹤從用戶的角度來看 – lax

回答

0

您可以使用Server.GetLastError訪問錯誤;

var exception = Server.GetLastError(); 
    if (exception != null) 
    { 
     //Display Information here 
    } 

欲瞭解更多信息:HttpServerUtility.GetLastError Method

+0

是這種有效的方式..我必須在每個頁面上面放置..應該我只處理主頁上的任何錯誤.. – lax

4

您可以在Global.asax中處理:

protected void Application_Error(object sender, EventArgs e) 
{ 
    Exception ex = System.Web.HttpContext.Current.Error; 
    //Use here 
    System.Web.HttpContext.Current.ClearError(); 
    //Write custom error page in response 
    System.Web.HttpContext.Current.Response.Write(customErrorPageContent); 
    System.Web.HttpContext.Current.Response.StatusCode = 500; 
} 
1

使用Elmah DLL與漂亮的UI顯示您的錯誤。您可以使用此DLL維護日誌。

2

請不要使用重定向作爲顯示錯誤消息的手段,因爲它會中斷HTTP。如果發生錯誤,服務器返回適當的4xx或5xx響應,而不是301重定向到200 OK響應是有意義的。我不知道爲什麼Microsoft將此選項添加到ASP.NET的自定義錯誤頁面功能,但幸運的是,您不需要使用它。

我建議使用IIS管理器爲您生成web.config文件。至於處理錯誤,請打開您的Global.asax.cs文件併爲Application_Error添加方法,然後從中調用Server.GetLastError()

+0

Dai我必須在ErrorPage.aspx上編寫有關錯誤的詳細信息和堆棧跟蹤 – lax

1

在Global.asax

void Application_Error(object sender, EventArgs e) 
{  
    Session["error"] = Server.GetLastError().InnerException; 
} 
void Session_Start(object sender, EventArgs e) 
{  
    Session["error"] = null; 
} 

在Error_Page Page_Load事件

if (Session["error"] != null) 
{ 
    // You have the error, do what you want 
} 
+1

由於在觸發Application_Error事件時Session對象不可用,因此無法使用。 – Arthur