1
votes

I was learning about the HttpContext and found out that

HttpContext object will be constructed newly for every request given to an ASP.Net application

Now, consider a case, when I have two pages. WebForm1 and Webform2. In Form1, I am writing the below mentioned code and redirects to form2.

HttpContext.Current.Items.Add("Key", "Value");

Query

When I use Server.Transfer this key persist and this is not the case while using Response.Redirect

Confusion

Wnenever a new request is generated, HttpCopntext object is created. Moreover, Session is preserved. Which is part of HttpContext.

HttpContext.Current.Session

If Session can persist, why can't HttpContext.Current.Items in Response.Redirect?

2

2 Answers

4
votes

The redirect generates a new HttpContext which is why the items in it are lost - the redirect effectively tells the browser the next URL to request, and when it does it loses the context of the previous request that triggered the redirect.

The session persists across requests (typically using a sessionID cookie to tie the user to values on the server), and is thus still available.

1
votes

I recommend to you to look with dotPeek at System.Web.dll, in particular at property HttpContext.Session that uses in getter HttpContext.Items["AspSession"] and at method SessionStateModule.InitStateStoreItem(...) (called in that getter) wich calls SessionStateUtility.AddHttpSessionStateToContext(...). You can see, that content of HttpSessionState collection is stored between requests in SessionStateStoreProviderBase implemented (InProc, Sql) object, more deeper in one word. Whereas HttpContext.Items hashtable is initialized at first get and dies between requests.