.net “检测”与Microsoft.AspNetCore.Session的过期会话

5uzkadbs  于 2023-03-24  发布在  .NET
关注(0)|答案(1)|浏览(156)

我正在ASP.NETCore中使用Microsoft.AspNetCore.Session包进行会话和状态管理。
有没有什么方法可以“检测”过期的会话,并在它过期时自动重定向到另一个视图?我在microsoft documentation中找不到任何关于这个特定用例的信息。

vuktfyat

vuktfyat1#

您可以先获取会话的到期时间,然后编写一个计时器,在会话到期时强制重定向到某个页面。
下面是我的测试代码,大家可以参考一下。
我在Program.cs中将会话过期时间设置为10秒:

builder.Services.AddSession(option =>
{
    option.IdleTimeout = TimeSpan.FromSeconds(10);
});

在我的控制器中有一个操作Time来获取会话的到期时间,还有另一个需要重定向的页面:

public class HomeController : Controller
{
    //get the expiration time of session
    public int Time()
    {
        var value = GetInstanceField(typeof(DistributedSession), HttpContext.Session, "_idleTimeout").ToString();
        string[] time = value.Split(':');
        var seconds = int.Parse(time[0])*60+ int.Parse(time[1]) * 60 + int.Parse(time[2]);
        return seconds;
    }
    private object GetInstanceField(Type type, ISession session, string v)
    {
        BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
        FieldInfo field = type.GetField(v, bindFlags);
        return field.GetValue(session);
    }
    //the page to redirect
    public IActionResult Test()
    {
        return View();
    }
}

然后请求"/Home/Time"并在_Layout.cshtml中设置计时器:

<script>
    var value;
    $.ajax({
        type: "GET",
        url: "/Home/Time",
        async: false,
        success: function (response) {
            value = response;
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
    const sessionTime = function() {
        value = value - 1;

        if (value <= 0){
            window.location.href = "/Home/Test";
        }
    };
    setInterval(sessionTime, 1000);
</script>

当程序运行10秒后,它将自动重定向到/Home/Test页面:

相关问题