ASP.NET Core MVC:会话过期事件?

问题描述 投票:0回答:1

在 ASP.NET Core 中,我们使用以下方法配置会话超时:

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

是否有一个我可以订阅的活动,以便在旧会话被放弃时收到通知?

换句话说:“Global.asax”中

Session_End()
的 .NET Core 替代品是什么?

c# asp.net-core-mvc
1个回答
1
投票

不,现在asp.net core中没有session_end事件。

这里有一个解决方法,我们可以编写一个自定义中间件来检查请求的会话是否存在。

注意,这个中间件将为每个请求运行,如下所示:

        app.Use(async (context, next) =>
        {
            if (context.Session != null)
            {
                var session = context.Session;

                // Check if the session has expired or has been abandoned
                if (!session.IsAvailable)
                {
                    // Trigger your event here
                    OnSessionAbandoned(session.Id);
                }
            }


            await next();
        });
© www.soinside.com 2019 - 2024. All rights reserved.