I have an ASP.NET application and in the Global.asax ‘ Application Error Event, I am calling a method to trace/log the error. I want to use the session variable content here. I used the below code
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("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3541504641755258545c591b565a58">[email protected]</a>", "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5347575a7e59535f5752105d5153">[email protected]</a>", "Error in " + Request.Form.ToString(), strError, 2);
}
I am getting an error in the line of code where I am accessing the session variable. Visual Studio is telling that
Session is not available in this context
How can I get rid of this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
It should work if you do it like this:
strError = System.Web.HttpContext.Current.Session["trCustomerEmail"]
Because that is what I do myself.
What exactly do you mean with: Visual Studio is telling that “Session is not available in this context”? Do you get a compiler error or a run-time exception?
You could try to be more defensive and test if there actually is a current HttpContext and a Session:
if (HttpContext.Current != null &&
HttpContext.Current.Session != null) {
strError = HttpContext.Current.Session["trCustomerEmail"]
}
Method 2
I think applicaiton error is specific for the whole application and a session is specific for the user. Maybe you can throw your own Exception where you save the information from the session inside your exception.
Method 3
You may try this:
HttpContext context = ((HttpApplication)sender).Context;
then you must use is like this:
context.Request.QueryString.ToString() context.Session["key"] = "fasfaasf";
but if the exception was thrown before the Session object is loaded, it will be null
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0