How is HttpContext being maintained over request-response

风流意气都作罢 提交于 2019-12-02 05:07:18

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!