'ASP.NET not sending session cookie
What would cause ASP.NET to not send a session cookie to the client?
I've noticed that, first of all, "ASP.NET_SessionId" cookie is set in both the Request.Cookies
and Response.Cookies
collections. Interestingly, the cookie was not actually part of the request, but the Request.Cookies
collection seems to be a dynamic combination of cookies actually sent with the request and cookies in the response. So if you add a cookie to the Response.Cookies
collection, it will be immediately be reflected in the Request.Cookies
collection.
Anyway.... the cookie is definitely in the Response.Cookies
collection. You can even get it in there twice by calling new SessionIDManager().SaveSessionID(HttpContext.Current, HttpContext.Current.Session.SessionID, out redirected, out cookieAdded)
, and cookieAdded will return true and there will now be two entries named "ASP.NET_SessionId" instead of one.
But the cookie is never sent with the response. What code or set of conditions decides to not send the "ASP.NET_SessionId" cookie with the response even though it's in the Response.Cookies
collection?
The conditions I have right now that seem to be triggering it is that I have my MVC base controller marked as [SessionState(SessionStateBehavior.ReadOnly)]
, which is necessary in order for multiple simultaneously AJAX requests to be processed in parallel by ASP.NET MVC; otherwise, it considers session a shared state and serializes processing of requests under the same session id. Since I"m not storing data in the "real" session which is marked as read-only, I'm actually storing session data in a static location and managing concurrency myself, but I'm still using the ASP.NET-generated SessionID to track it (clever, eh?). Problem is, without the cookie being sent, the SessionID is changing with every new request, so I lose track of the user's session every time. I cannot seem to force the system to send the cookie; something is intentionally not sending it.
Solution 1:[1]
This causes from the behavior of SessionStateModule. SessionStateModule sets the "ASP.NET_SessionId" cookie in the Response.Cookies collections in AcquireRequestState event when "ASP.NET_SessionId" cookie is not sent from the client. Then if nothing is stored in the session, SessionStateModule deletes the "ASP.NET_SessionId" cookie in ReleaseRequestState event. If you set the "ASP.NET_SessionId" cookie in the Response.Cookies collections manually and nothing is stored, then SessionStateModule deletes all the "ASP.NET_SessionId" cookies including the cookie you set.
If you want to track the client, you should use a cookie with a name other than "ASP.NET_SessionId" or add "ASP.NET_SessionId" cookie manually after ReleaseRequestState event.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kazuki Yoshimoto |