How to maintain the same session id across multiple web applications in ASP.NET

Saturn K picture Saturn K · Jul 9, 2010 · Viewed 17.3k times · Source

I have two identical applications setup on IIS on different virtual directories (I have done some workaround to ensure that they both have the same application name). Is there a way to share session id across two asp.net web applications?

Since I'm storing the session in StateServer, they should both be getting the same session data, however, a different session id is created everytime I go from application a to applicatino b. Wouldn't this happen in a load balancing scenario as well? Where when I go to www.test.com, it would redirect that request to server a, and then if I hit it again, it would go to server b, but since it's a different web application, it would create a new session id?

Answer

matt-dot-net picture matt-dot-net · Jul 9, 2010

First, configure the sessionState element in your web.config to use cookieName="SOME_COOKIE_NAME_HERE" in both apps.

Then, just make sure the urls have the same TLD (top-level domain), i.e. app1.mydomain.com and app2.mydomain.com and you should be able to handle the Session_Start event in Global.asax and put this code:

    HttpCookie cookie = new HttpCookie("SOME_COOKIE_NAME_HERE", Session.SessionID.ToString());
    cookie.Expires = DateTime.Now.AddMinutes(20);
    cookie.Domain = "*.mydomain.com";
    cookie.HttpOnly = true;
    Response.SetCookie(cookie);

Also, I would recommend that you go with the SqlServer SessionState Mode.