次の方法で共有


A case of lost session variables when using out of process session state

Recently I had a case where the customer had an issue with session variables.  The claim was that if they use in-proc session state their session variables would work just fine, but if they changed the session mode to stateserver in web.config their sessions were lost.

<sessionState mode="StateServer" cookieless="UseCookies" stateConnectionString="tcpip=127.0.0.1:42424"/>

When looking at bit closer at the repro, it wasn’t really all session variables that were lost, it was only ones set in Page_Error, and when they were read in an error page they redirected to (with the customErrors setting in web.config) would be null.

Why is there a difference in this case between in-proc and out of process session state?

When you use in-proc session state, the session objects are stored in the memory of the process, and thus when you run code like Session[“mySessionVar”] = “some value”;  it is immediately written to that session variable.

With out-of-proc session state on the other hand (stateserver or sqlsessionstate), all session variables for the current session are read from the store at the beginning of each request, and then any changes are committed back to the session store at the end of the request.

In a case where an exception occurs, the request is effectively aborted so none of the changes that are made to the session during that request are written back to the store.  

Old session variables and values will still be intact though…

So how do you handle this situation in a case where you use state server or SQL session state?

If you want to use session state to store values relating to errors in pages that should be available in an error page you can clear the error in page_error and manually redirect to the error page.

The code could look something like this:

protected void Page_Error(object sender, EventArgs e)
{
    Session["ErrorPage"] = "Default2.aspx";
    Exception ex = Server.GetLastError();
    Session["ErrorMessage"] = ex.Message.ToString();
    Server.ClearError();
    Response.Redirect("~/ErrorPages/ErrorPage.aspx");
}

Clearing the error allows the request to finish processing and the session variables to be committed to the store.

Laters,
Tess