Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle the error message: Session state is not available in this context

Tags:

c#

asp.net

I am trying to create an error message page to display exception when exception occurs, and there is a return button on error message page to return the previous page where the exception caused.

here is the code used to redirect the error page.

protected void btnAssign_Click(object sender, EventArgs e)
{
    try
    {
        SqlDataSource3.Insert();
    }
    catch (Exception ex)
    {
        Session["Exception"] = ex;
        Response.Redirect("~/ErrorMessage.aspx", false);
    } 
}

here is the code for my global.asax file

void Application_Error(object sender, EventArgs e) 
{ 
    // Code that runs when an unhandled error occurs
    Exception ex = Server.GetLastError().InnerException;
    Session["Exception"] = ex;
    Response.Redirect("~/ErrorMessage.aspx");
}

here is the code for errorMessage page.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Exception ex = (Exception)Session["Exception"];
            Session.Remove("Exception");
            Literal1.Text = "<p style='color:blue'><b>An unrecoverable error has occurred:</b></p><br /><p style='color:red'>" + ex.Message + "</p>";
        }  
    }
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/IncidentAssignment.aspx");
    }

When I click the assign button, it opens the errorMessage page and display the exception, but when I click return button, the program crashed and pointed to global.asax file and says Session state is not available in this context, as shown in blew. enter image description here

I don't get it why is the session["exception"] Null. it will be much appreciated if anyone answered my question. Thanks.

like image 662
mrqyue Avatar asked Feb 22 '13 04:02

mrqyue


2 Answers

you are trying to access session state in application error event where it might be that your session object is not being initialized. error might be thrown at some other location your application since it refers to whole application.

Commonly this happens when your error thrown is at your applications initial stages so that session object not being initialized.eg. in Begin_Request event.

You could do null check before accessing the session object.

ie

if (HttpContext.Current.Session != null) { //do your stuff}
like image 71
DSharper Avatar answered Oct 16 '22 10:10

DSharper


Instead of using the line of code that is located inside of your :

protected void btnReturn_Click(object sender, EventArgs e)
{
    Response.Redirect("~/IncidentAssignment.aspx");
}

Get rid of that completely, and in your HTML code of your button, add this line of code:

PostBackUrl="insert your path here"

Therefore, it should lead you back to the page you started.

like image 31
user1955712 Avatar answered Oct 16 '22 12:10

user1955712