在 ASP.NET Core 中,我们使用以下方法配置会话超时:
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
});
是否有一个我可以订阅的活动,以便在旧会话被放弃时收到通知?
换句话说:“Global.asax”中
Session_End()
的 .NET Core 替代品是什么?
不,现在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();
});