如何减少 ASP.NET Core 中的 cookie 大小(类似于使用引用模式)?

How to reduce cookie size in ASP.NET Core (something similar to using reference mode)?

我正在实施一个 ASP.NET 核心 Web 应用程序,它使用 cookie 和 WS-Federation 身份验证(如果 cookie 存在并且有效,它会使用它,否则它会向身份提供者询问 SAML 令牌,如果用户是已登录)。

我在 .NET 的 Web API 项目中进行了很好的设置。对于cookie认证,我用System.IdentityModel.Services.SessionAuthenticationModule来帮忙。更具体地说,它具有我设置为 true 的 IsReferenceMode 属性,从而允许在整个会话期间将 cookie 存储在服务器端缓存中。这只允许在客户端和服务器之间传递对 cookie 的引用,这有助于减小 cookie 的大小。

显然 ASP.NET Core 不直接支持此功能,因为 System.IdentityModel 不兼容。我想知道是否有类似的事情我可以做。

我见过类似的问题here and ,但都没有真正帮助我。

编辑:Jan Hajek 的 This article on session state from the Microsoft docs and this blog article 看起来他们可以为我提供答案。

您可以使用实现 ITicketStore 的简单 MemoryCacheTicketStore 并像这样配置您的 cookie:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ApplicationScheme;
})
.AddIdentityCookies(options => options.ApplicationCookie.Configure(configureOptions =>
    {
        configureOptions.SessionStore = new MemoryCacheTicketStore(ApplicationSettings.Current.AuthenticationTimeOut);
    })
);

这取自 GitHub 样本,please have a look at it