Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.Items["value"] not working because AngularJS calls create new sessions

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;
like image 670
Jim Avatar asked Aug 04 '15 16:08

Jim


1 Answers

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.

like image 97
NightOwl888 Avatar answered Oct 22 '22 04:10

NightOwl888