在 AddSession() 中使用虚拟目录配置 Cookie 路径

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

我想将 .ASPNetCoreSession cookie 的路径设置为当前托管应用程序的虚拟目录。这当然应该动态发生。目前路径默认设置为/

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;
    });

anti forgery token implementation 已经按预期做到了这一点,我想做类似的事情。

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

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

不幸的是,此实现受限于 HttpContext

我正在考虑使用 IPostConfigureOptions<T>IConfigureOptions<T> 来使用 DI,但只要我需要访问当前的 HttpContext 范围,我就看不到这样做的方法。

我确定一定有其他方法可以在 Startup.cs class?

中检索虚拟目录

虽然我不是这个选项的超级粉丝,但暂时我会添加我自己的 SessionMiddleware(它在 Configure 中注册为 UseSession() 的一部分Startup.cs) 中的方法,我将从 HttpContext 检索虚拟目录并通过 CookieBuilder.

设置 Cookie.Path