views:

59

answers:

2

THE CODE:

Session["foo"] = "bar";  
Response.Redirect("foo.aspx");

THE PROBLEM:

When foo.aspx reads "foo" from the session, it's not there. The session is there, but there's no value for "foo".

I've observed this intermittently in our production environment. But I don't mean here to ask a question about Response.Redirect().

THE EXPLANATION:

Bertrand Le Roy explains (the bolding is mine):

Now, what Redirect does is to send a special header to the client so that it asks the server for a different page than the one it was waiting for. Server-side, after sending this header, Redirect ends the response. This is a very violent thing to do. Response.End actually stops the execution of the page wherever it is using a ThreadAbortException. What happens really here is that the session token gets lost in the battle.

My takeaway there is that Response.Redirect() can be heavy-handed with ending threads. And that can threaten my session writes if they occur too near that heavy-handedness.

THE QUESTION:

What about ASP.NET session management makes it so vulnerable to this? The Response.Redirect() line of code doesn't begin its execution until the session write line is "finished" -- how can it be such a threat to my session write?

What about the session write doesn't "finish" before the next line of code executes? Are there other scenarios in which session writes are similarly (as though they never occurred) lost?

+1  A: 

I'm not familiar enough with the internals of session writing, but I imagine it has some complexities, as it relies on translating the browser session cookies into a server identification. Additionally, ThreadAbortExceptions do have special considerations in the runtime, which may play in here, I'm not sure.

In any case, Response.Redirect() has an overload that takes a boolean parameter that lets you specify whether you want to end the thread or not.

Response.Redirect(string url,  bool endResponse);

If you call it with endResponse set to "false", it will gracefully finish, rather than calling Thread.Abort() internally. However, this means it will also execute any code left in the page lifecycle before finishing up.

A good compromise is to call Response.Redirect(url, false) followed by Application.CompleteRequest(). This will allow your redirect to happen but also gracefully shut down the current execution context with a minimal amount of additional lifecycle processing.

womp
A: 

Application pool recycle can cause your session to go away. You can configure the app pool to recycle at fixed times (recommended, and at night or during low-usage periods) or increase the timeout period of your app pool recycle.

Gene