Search code examples
c#asp.net-mvccookies.net-corekestrel

Configure the Cookie Path with a Virtual Directory in AddSession()


I would like to set the path of the .ASPNetCoreSession cookie to the virtual directory in which the application is currently hosted in. This should of course happen dynamically. Currently the path is set to / by default.

services.AddSession(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.Path = "/MyVirtual/DirectoryPath";
        options.Cookie.Name = SessionCookieName;
        options.IdleTimeout = TimeSpan.FromMinutes(15);
        options.Cookie.SameSite = SameSiteMode.Strict;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    });

The anti forgery token implementation already does this out of the box as intended and I would like to do something similar to that.

  var pathBase = httpContext.Request.PathBase.ToString();

  if (!string.IsNullOrEmpty(pathBase))
  {
      options.Path = pathBase;
  }

Unfortunately this implementation is bounded to the HttpContext.

I was thinking about using IPostConfigureOptions<T> or IConfigureOptions<T> to make use of DI but as long as I need to access the current HttpContext which is scoped I don't see a way to do that.

I am sure there must be other ways to retrieve the virtual directory within the Startup.cs class?


Solution

  • Although I am not a huge fan of this option but for the time being I will just add my own SessionMiddleware (which is registered as part of UseSession() in the Configure method in Startup.cs) where I will retrieve the virtual directory from the HttpContext and set Cookie.Path via the CookieBuilder.