I've recently ran into a bit of trouble with maintaining the aspnet session state across a subdomains of the same application.
The main problem was that the ASPNET SessionID cookie by default points to the full web address, meaning that when you
navigate to a subdomain, aspnet creates a new SessionID cookie for that subdomain and doesnt read the root domains session cookie.
In short, you loose your session variables/authentication info when you browse to subdomains of your site.
Now, had I been using Forms Authentication, I could have set my cookie domain to ".mydomain.com" in the web.config. Problem solved, but alas I was using the inproc session state and there is no cookie attribute specify a fixed cookie domain.
So lets take a look at one solution that worked for this scenario.
So to ensure that my session cookie pointed to the correct domain I needed to set the correct domain on every page request.
The global.asax has an event which is perfect for this application called Application_PreRequestHandlerExecute
which fires just before a page is loaded.
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs
/// only apply session cookie persistence to requests
requiring session information
#region session cookie
(Context.Handler is IRequiresSessionState ||
Context.Handler is IReadOnlySessionState )
/// Ensure ASP.NET Session Cookies are accessible throughout
!= null && Session != null && Session.SessionID != null)
Response.Cookies["ASP.NET_SessionId"].Domain = ".know24.net"; // the full stop prefix denotes all sub domains
Response.Cookies["ASP.NET_SessionId"].Path = "/"; //default
session cookie path root
Firstly, we filter any requests not involved with the session. Many Ajax type requests dont use sessions and any attempt to access it will throw exceptions.
Secondly, we check if the ASP.NET SessionId cookie exists, if the session exists and a valid session ID is present.
Finally, we set the ASP.NET Session Cookie's Value to the current Session ID. Followed by setting the domain full stop, notice the full prefixed full stop "." which indicates that it is accessible to all subdomains of the domain know24.net.
You'll see that the path property also gets set, this is due to some folks reporting that ASP.NET doesnt recognise all cookie changes unless this Path attribute is reset. I've not confirmed this yet so we have it here for just in case.
I would also recommend you implement the method below to cleanup any cookies when log your users out.
As you may know, ASP.NET cannot delete cookies on the client, so the best alternative is to overwrite them and set them to expired to trigger the browsers cookie delete routine when the browser closes.
/// delete all cookies
iCookieCount = HttpContext.Current.Request.Cookies.Count;
for (int i = 0; i < iCookieCount; i++)
httpCookie = new
httpCookie.Expires = DateTime.Now.AddDays(-1);
I hope this helps some of you who get stuck with a similar problem.