0

How can I list (and iterate through) all current ASP.NET Core sessions?

In pre-Core times we had the option to listen to Session_Start and Session_End events --> List all active ASP.NET Sessions

What can we do in Core as there are not such events? I found a workround for Session_Start but nothing for Session_End so far. Then again, maybe there is a completely different approach that can be used with ASP.NET Core?

Jack Miller
  • 6,843
  • 3
  • 48
  • 66

1 Answers1

0

You can use database such as Redis to get all user sessions. https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-7.0

Redis is very simple to deploy.
1.Download from https://github.com/tporadowski/redis/releases "Redis-x64-5.0.14.1.zip" execute "redis-server.exe" Then you host a redis server at port 6379.
enter image description here 2.In Asp.net Core project, install package "windows.extensions.caching.stackexchangeredis." And register service. Sessions will automatically using redis with this simple configuration.

builder.Services.AddStackExchangeRedisCache(option =>
{
    option.Configuration = "localhost";
});

3.Now you can use the following code to get all sessions in the redis server.
ConnectionMultiplexer multiplexer = ConnectionMultiplexer.Connect("localhost:6379,allowAdmin=True,connectTimeout=60000");
var AllSessions = multiplexer.GetServer("localhost:6379").Keys();
Console.WriteLine(string.Join(",", AllSessions));

enter image description here
It is same if you check sessions using redis destop manager enter image description here

For Session_End there seems no samples to write a middleware. https://github.com/dotnet/AspNetCore.Docs/issues/11869

Qiang Fu
  • 1,401
  • 1
  • 2
  • 8