Search code examples
asp.netsessionsession-state

ASP.NET Session State Server: Stored Object is NULL


I have set up an ASP.NET Session State Server on a SQL Database:

<sessionState timeout="60" allowCustomSqlDatabase="true" mode="SQLServer" sqlConnectionString="..." />

I have a default redirect on errors:

<customErrors mode="On" defaultRedirect="~/Error.aspx" />

Global.asax.cs:

private void Application_Error( object sender, EventArgs e )
{
    SomeSessionObj sessionObj = new SomeSessionObj();
    sessionObj.SomeProperty1 = true;
    sessionObj.SomeProperty2 = new Blabla();
    HttpContext.Current.Session["FooBar"] = sessionObj;
}

Error.aspx.cs:

protected void Page_Load( object sender, EventArgs e )
{
    SomeSessionObj sessionObj = HttpContext.Current.Session["FooBar"] as SomeSessionObj;
    // sessionObj is NOT NULL
    // sessionObj.SomeProperty1 is false
    // sessionObj.SomeProperty2 is NULL
}

Both SomeSessionObj and SomeProperty classes are marked as Serializable.

Without State Server (inProc) it works as expected.

Thanks in advance.


Solution

  • Ok, got it working.

    When using Session State Server you have to call Server.ClearError() within Application_Error, otherwise the Request will be terminated and Session state will not be written.

    void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        HttpContext.Current.Session["Error"] = ex.Message;
        Response.Redirect("error.aspx",false);
        Server.ClearError();  
    }