本文将向您展示如何在 ASP.NET Core 运用程序中实现这一目标。
实现事理Cookie 具有一个 Domain 属性,该属性指定哪个做事器可以吸收 Cookie。如果指定了 Domain,则 Cookie 可用于该做事器及其子域。例如,如果您设置 Domain=.koudingke.cn,则 Cookie 可用于 koudingke.cn 及其子域,如 blogs.koudingke.cn。
如果做事器没有指定 Domain,则 Cookie 仅在该做事器上可用,而不在其子域上可用。因此,指定 Domain 比省略 Domain 更不限定。然而,在子域之间须要共享用户信息时,指定 Domain 可能会有帮助。

在 ASP.NET Core 中有一个 CookiePolicyMiddleware,您可以在添加或删除 Cookie 时向 CookiePolicyOptions 添加一些策略。
我们将在 CookiePolicyOptions 中添加一个策略,以变动 Cookie 的域:
services.Configure<CookiePolicyOptions>(options =>{ options.OnAppendCookie = cookieContext => { ChangeCookieDomain(cookieContext, null); }; options.OnDeleteCookie = cookieContext => { ChangeCookieDomain(null, cookieContext); };});private static void ChangeCookieDomain(AppendCookieContext appendCookieContext, DeleteCookieContext deleteCookieContext){ if (appendCookieContext != null) { // Change the domain of all cookies //appendCookieContext.CookieOptions.Domain = ".koudingke.cn"; // Change the domain of the specific cookie if (appendCookieContext.CookieName == ".AspNetCore.Culture") { appendCookieContext.CookieOptions.Domain = ".koudingke.cn"; } } if (deleteCookieContext != null) { // Change the domain of all cookies //appendCookieContext.CookieOptions.Domain = ".koudingke.cn"; // Change the domain of the specific cookie if (deleteCookieContext.CookieName == ".AspNetCore.Culture") { deleteCookieContext.CookieOptions.Domain = ".koudingke.cn"; } }}
在 ASP.NET Core 管道中添加 app.UseCookiePolicy():
//...app.UseStaticFiles();app.UseCookiePolicy();//...
如果您检讨 HTTP 相应头,将看到 Set-Cookie 头,个中包含域属性,如下所示:现在,子域可以共享 .AspNetCore.Culture Cookie。
总结CookiePolicy 中间件供应了一种在 ASP.NET Core 中掌握 Cookie 的办法,如果您对 Cookies 有更繁芜的需求,它非常有用。