ASP.NET:如何在global.asax中访问Session变量

8

我有一个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提示:

此上下文中无法使用会话

我该如何解决这个问题?


错误是从哪里抛出的?在aspx代码后台(哪个事件?)还是在http处理程序中?这可以确定是否有效使用会话对象。 - JonoW
3个回答

12

如果你按照以下方式操作,它应该可以正常工作:

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

因为那是我自己做的。

你所说的"Visual Studio告诉我“在此上下文中不可用”的Session是指什么?你得到了编译器错误还是运行时异常?

你可以尝试更具防御性的方法,测试当前是否有HttpContext和Session:

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

你能否发布访问Session时收到的异常消息以及你正在尝试处理的异常消息? - Remko Jansen

3

我认为应用程序错误是针对整个应用程序的,而会话是针对用户的。也许您可以抛出自己的异常,在其中保存来自会话的信息。


是的,Applicationxxxx 事件是特定于您的应用程序的,而不是特定于会话的。 - Icebob

1
您可以尝试这个:
HttpContext context = ((HttpApplication)sender).Context;

那么你必须像这样使用:

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

但如果异常在加载Session对象之前抛出,那么它将为null


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接