views:

608

answers:

2

I am wondering how the HttpContext is maintained given that the request-response nature of the web is essentially stateless.

Is an identifier being for the HttpContext object being sent as part of the __EVENTTarget / __EVENTARGUMENTS hidden fields so that the HttpRuntime class can create the HttpContext class by reading this section from the request (HttpWorkerRequest)? I don't think

Please let me know as I am trying to fill some holes in my understanding of the http pipeline and I was unable to find any information about this.

I understand something like HttpContext.Current.Session["myKey"] = Value;

just works but if I had to do something similar in a different language (say perl), I would have to use hidden fields for the same, wouldn't I?

Thanks -Venu

A: 

I don't think there is one answer to your question, because I don't think everything under the HttpContext umbrella works the same way. In the example you chose, session state, both the key and value are stored on the server side. The way it knows how to hook up future requests to that session state is by using a cookie that has a (totally different) key in it. When the browser makes another request, it sends this cookie with the request and the server uses it to figure out which session to map to. Once it figures it out, you've again got access to your dictionary, across responses.

So, to do it in perl, you'd want to manually create a cookie and store a unique key in it, have a server-side mapping of those unique keys to session state dictionaries, and pretty much do what I described above.

Greg
+5  A: 

The HttpContext is recreated for each request. The HttpSession, however, is stored on the server across requests. Basically, HttpSession is a Dictionary<string, Dictionary<string, object>>. The initial key, the session id, is provided by either a cookie or a query string parameter (if using cookie-less sessions). If you use Fiddler, you'll see the ASP.NET_SessionId cookie that contains the key for that user's session.

In code:

class HttpSessionState {
   private static readonly Sessions = 
     new Dictionary<string, Dictionary<string, object>>();

   public object this(string key) {
      get {
         return GetCurrentUserSession()[key]
      }
      set {
         GetCurrentUserSession()[key] = value;
      }
   }

   private Dictionary<string, object> GetCurrentUserSession() {
      var id = GetCurrentUserSessionId[]
      var d = Sessions[id];
      if (d == null) {
         d = new Dictionary<string, object>();
         Sessions[id] = d;
      }
      return d;
   }

   private string GetCurrentUserSessionId() {
      return HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value;
   }
}

The real implementation also handles session timeouts, abandons, and cookieless sessions - but the basic idea is the same.

Mark Brackett