.NET Core 3.1 Web 会话超时

问题描述

我正在使用 IIS 托管一个 C# 网站(.NET Core 3.1)。我已将 IIS 应用程序池的“空闲超时(分钟)”设置为 150。我已重新启动网站并回收应用程序池。

身份验证通过 Microsoft.AspNetCore.Identity.SignInManager 完成。

用户登录,但他们的登录会话在 45 分钟不活动后自动过期。我不知道他们是在什么时候准确注销的(我猜是 20 分钟)。

由于 IIS 会话注销是 150 分钟,为什么用户在不到 45 分钟内注销?

有没有办法使用 IIS、appsettings.json 或 web.config 使他们的会话持续最少 150 分钟?

我想我可以用代码做到这一点:

services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(3);
});

... 并且可能从 aspsettings.json 读取该值,但我不想对该值进行硬编码,因为它可能会因环境而异。

解决方法

我发现了这个问题。在 Starup.cs 中发现:

services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Account/Login";
    options.LogoutPath = "/Account/Logout";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
});

为了我的理智,我将其更改为:

int timeoutInMinutes = 30;
try
{
    timeoutInMinutes = Int32.Parse(Configuration.GetSection("AppSettings:SessionTimeoutInMinutes").Value);
}
catch (Exception) { } // do nothing

services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Account/Login";
    options.LogoutPath = "/Account/Logout";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(timeoutInMinutes);
});

进行此更改后,如果未在 appsettings.json 中更改,登录会话现在将在 30 分钟后过期,否则它将使用我在 appsettings.json 中指定的值。