ASP.NET 核心 - 如何以编程方式重新启动会话超时

ASP.NET Core - How to restart session timeout programatically

我正在将 .NET 4 Framework ASP.NET MVC 项目迁移到 .NET Core,并且我有以下控制器方法 (.NET 4):

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] // Never Cache
public virtual ActionResult Extend()
{
     // Re-establish the session timeout
     Session.Timeout = Utility.Constants.sessionTimout;
     return new EmptyResult();
}

这是我在 .NET Core 中的代码

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
//[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] // Never Cache
public virtual ActionResult Extend()
{
    // Re-establish the session timeout
    // TODO: Need to find out in ASP.NET CORE
    
    //this.HttpContext.SessionSession.Timeout = Utility.Constants.sessionTimout;
    return new EmptyResult();
}

我一直在尝试找出如何在 .NET Core 中执行 Session.Timeout 但运气不佳。

** 更新 ** 此方法从加载到 IFrame 的外部应用程序重新启动超时。因此,当用户在 iFrame 应用程序中时,主 ASP.NET 应用程序根本没有进行任何交互。所以这就是我需要从 iFrame 应用程序手动延长会话超时的原因。

有线索吗?

我不熟悉 .net 核心中可用的 TimeOut 属性。

但是,可以使用 Session 描述的状态 here

您可以在设置过程中设置超时时间:

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(10);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

调用您的 Extend 操作应该足以重置空闲计时器。

请记住,访问 Session 状态在 .net 核心中是不同的,例如:

HttpContext.Session.SetString("foo", "bar");
string foo = HttpContext.Session.GetString("foo");

通常,即使在 IFrame 内,使用与页面的交互也足以重置 IdleTimeout

作为@Aria,您甚至可以检测即将到来的超时并采取相应措施。