Asp.net
ASP.NET:訪問 global.asax 中的 Session 變數
我有一個 ASP.NET 應用程序,在 Global.asax 的應用程序錯誤事件中,我正在呼叫一個方法來跟踪/記錄錯誤。我想在這裡使用會話變數內容。我使用了下面的程式碼
void Application_Error(object sender, EventArgs e) { //get reference to the source of the exception chain Exception ex = Server.GetLastError().GetBaseException(); //log the details of the exception and page state to the //Windows 2000 Event Log GUI.MailClass objMail = new GUI.MailClass(); string strError = "MESSAGE: " + ex.Message + "<br><br><br>" + "SOURCE: " + ex.Source + "<br>FORM: " + Request.Form.ToString() + "<br>QUERYSTRING: " + Request.QueryString.ToString() + "<br>TARGETSITE: " + ex.TargetSite + "<br>STACKTRACE: " + ex.StackTrace; if (System.Web.HttpContext.Current.Session["trCustomerEmail"] != null) { strError = "Customer Email : " + Session["trCustomerEmail"].ToString() +"<br />"+ strError; } //Call a method to send the error details as an Email objMail.sendMail("test@gmail.com", "myid@gmail.com", "Error in " + Request.Form.ToString(), strError, 2); }我在訪問會話變數的程式碼行中遇到錯誤。Visual Studio 告訴我們
會話在此上下文中不可用
我怎樣才能擺脫這個?
如果您這樣做,它應該可以工作:
strError = System.Web.HttpContext.Current.Session["trCustomerEmail"]因為那是我自己做的。
您到底是什麼意思:Visual Studio 告訴“會話在此上下文中不可用”?您是否收到編譯器錯誤或執行時異常?
您可以嘗試更具防禦性並測試是否確實存在目前的 HttpContext 和 Session:
if (HttpContext.Current != null && HttpContext.Current.Session != null) { strError = HttpContext.Current.Session["trCustomerEmail"] }