ASP.NET:global.asax中的访问会话变量

问题描述 投票:8回答:3

我有一个ASP.NET应用程序,并且在Global.asax的Application Error Event中,我正在调用一种方法来跟踪/记录错误。我想在这里使用会话变量的内容。我用下面的代码

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("[email protected]", "[email protected]", "Error in " + Request.Form.ToString(), strError, 2);   
} 

我访问会话变量的代码行出现错误。 Visual Studio告诉

会话在这种情况下不可用

我该如何摆脱呢?

asp.net session global-asax
3个回答
11
投票

如果您这样做,它应该可以工作:

strError = System.Web.HttpContext.Current.Session["trCustomerEmail"]

因为那是我自己做的。

您的确切含义是:Visual Studio告诉“会话在此上下文中不可用”?您收到编译器错误或运行时异常吗?

您可以尝试更具防御性,并测试是否确实存在当前的HttpContext和一个Session:

if (HttpContext.Current != null &&
    HttpContext.Current.Session != null) {
  strError = HttpContext.Current.Session["trCustomerEmail"]
}

3
投票

我认为应用程序错误特定于整个应用程序,而会话则特定于用户。也许您可以抛出自己的异常,将异常中的会话信息保存在异常中。


1
投票

您可以尝试以下方法:

HttpContext context = ((HttpApplication)sender).Context;

然后您必须使用这样的代码:

context.Request.QueryString.ToString()
context.Session["key"] = "fasfaasf";

但是如果在加载Session对象之前引发了异常,它将为null

© www.soinside.com 2019 - 2024. All rights reserved.