Search code examples
iiscookiesweb-configsession-cookiessession-state

Change ASP.NET_sessionid cookie path using SessionIDManager


I'm renaming the cookie and made it to target to a different path, rather than targeting to a default path "/".

Below is the web.config settings:

<sessionState sessionIDManagerType="MyNamespace.MySessionIDManager" cookieName="AppCookie"/>

Below is the backend class used to create the cookie:

 public class MySessionIDManager : SessionIDManager, ISessionIDManager
{
    void ISessionIDManager.SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
    {
        base.SaveSessionID(context, id, out redirected, out cookieAdded);

        if (cookieAdded)
        {
            var name = "AppCookie";
            var cookie = context.Response.Cookies[name];
            cookie.Path = "/Forms";
        }
    }
}

This fix is working fine for me locally. The cookie is successfully pointing to the given path i.e "/Forms".

enter image description here

But when I deploy my application to IIS, I'm not able to login to the application. It is not throwing any error, but not allowing me to login to the web application.

If I use to below web.config settings, it is working fine.

<sessionState mode="InProc" timeout="30" cookieName="AppCookie" />

Please let me know what issue it is causing in the IIS. Any input is much appreciated.

Thank you all in advance.

Thanks and Regards, Dada.


Solution

  • I fixed this issue with the below piece of code;

    public class CookieManager : SessionIDManager, ISessionIDManager
    {
        void ISessionIDManager.SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
        {
            base.SaveSessionID(context, id, out redirected, out cookieAdded);
    
            if (cookieAdded)
            {
                SessionStateSection sessionStateSection = (System.Web.Configuration.SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
                var cookie = context.Response.Cookies[sessionStateSection.CookieName];
                cookie.Path = context.Request.ApplicationPath;
            }
        }
    }
    

    And update the web.config as follows;

    <sessionState sessionIDManagerType="ANJU.Reports.WebUI.Library.CookieManager" timeout="30" cookieName="CookieName"/>
    

    Now when I host my application on the IIS, it'll fetch the directory where I have my build. All my cookies will point to the root directory of the build.