I'm using C#, MVC and AngularJS.
My problem is that my MVC program creates a HttpContext.Current.Items["value"]
and sets the value in the initial home controller, but when my AngularJS hits the application with an ajax call, it creates a new session and I can't get the value I set earlier in my HttpContext.Current.Items["value"]
call.
Is there something I can do to fix this problem? I'd like to continue using HttpContext.Current.Items["value"]
.
Why do my AngularJS calls create new sessionids? The reason I know the sessions are new is because they have different ids when I use this:
String strSessionId = HttpContext.Session.SessionID;
HttpContext.Current.Items
is a dictionary for request caching only. As soon as the request is finished all of the values in it will go out of scope.
// Will last until the end of the current request
HttpContext.Current.Items["key"] = value;
// When the request is finished, the value can no longer be retrieved
var value = HttpContext.Current.Items["key"];
HttpContext.Current.Session
is a dictionary that stores data between requests.
// Will be stored until the user's session expires
HttpContext.Current.Session["key"] = value;
// You can retrieve the value again in the next request,
// until the session times out.
var value = HttpContext.Current.Session["key"];
The reason why your HttpRequest.Current.Items
value is not available again is because you are setting it "in your home controller", which is a completely separate request from your AJAX call.
Session state depends on a cookie, so if the same cookie is sent back to the server, the data stored there can be retrieved. Fortunately, if you are on the same domain, AJAX will automatically send the cookie back to the server.
As for the SessionID changing, ASP.NET does not allocate storage for session until it is used. So you need to explicitly store something in session state in order to actually start a session. See this MSDN article for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With