Tuesday, May 15, 2007

Neat session state trick

Just thought I'd share a neat little bit of code for handling session state in ASP.NET.

The trick is to create a class that keeps it's own sessionstate, like this:

public class CustomerSession
private string mName = "";
private string mTelephone = "";

// To enshure unique session key
private static string mGuid = "PlaceGUIDHere";

public string Name
get { return mName; }
set { mName = value; }

public string Telephone
get { return mTelephone; }
set { mTelephone = value; }

private CustomerSession() { }

public static CustomerSession GetInstance(HttpSessionState session)
CustomerSession o = (CustomerSession)session[mGuid];
if(o == null) {
o = new CustomerSession();
session[mGuid] = o;

return o;

Then you can save data in session like this:

protected void btnSave_Click(object sender, EventArgs e)
CustomerSession data = CustomerSession.GetInstance(Session);
data.Name = txtName.Text;
data.Telephone = txtTelephone.Text;

I heard about this in .NET Rocks! episode 82 where Richard Hale Shaw where speaking of his way of storing session state in a safe way. It's at about 54 minutes into the podcast episode if you want to check it out for yourself =)


Jesper said...

Thanks for this, it's very useful.

I have been looking for a way to transfer sessions between different application domains in a secure way, but been unable to find an solution. Do you have any idea how to do that?

Joakim said...

If it's only between sessions I guess you could make a wrapper like this around Application (Make sure you're Thread-Safe like Session is by default).

But between different application domains? Haven't really been doing much there yet, the first thing that comes to mind is to use the database as the middleman.

Don't know how applicable that is to your session problem tough.

Jesper said...

Thanks for the comment. I still haven't figured out to solve this problem.

Your idea to use the database could be a step in the right direction.

My idea this far has been to put together a hashed querystring, to use as a "ticket", to the session on the domain I want to move the user to. The problem has been, that it dowsn't matter how har I make this URL, if somebody, get hold to it (through web site statistics or simular) they would get access to the session.

Now I got a idea to include a time stamp into the hashed ticket. So that the URL would only work for 30 seconds or so. Other values to but in the hash could be user id, email for login and parhaps also the user's password.

But what bothers me, is that it's not going to be 100% safe. If somebody find the URL with in the 30 seconds, they got access to the application.