How to handle the error message: Session status in this context is not available

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

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 errorMessage page code.

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 displays an exception, but when I click the return button, the program crashed and pointed to the global.asax file and reported that the session state was not available in this context, as shown in the hollow. enter image description here

, [ "exception" ] Null. , - . .

+5
3

, , :

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

, HTML- :

PostBackUrl="insert your path here"

, .

+1

, , . , .

, , .eg. Begin_Request.

.

ie

if (HttpContext.Current.Session != null) { //do your stuff}
+6

When you define an error page in your web.config, then on the error page you can access the following exceptions:

HttpContext.Current.AllErrors

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/ErrorPage.aspx">
</customErrors>
0
source

All Articles