A lightweight ASP.NET Core middleware and controller combo that tracks user activity enabling you to monitor and manage session timeouts effectively.
$ dotnet add package SessionActivityTrackerSessionActivityTracker is a lightweight ASP.NET Core middleware and controller combo that tracks user activity enabling you to monitor and manage session timeouts effectively.
dotnet add package SessionActivityTracker
Startup.cs or Program.cs:using SessionActivityTracker;
using SessionActivityTracker.Extensions;
// ... other services
builder.Services.AddDistributedMemoryCache(); // Or Redis/SQL distributed cache
builder.Services.AddSession();
builder.Services.AddSessionActivityTracking(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20); // Set your desired timeout
});
app.UseSession();
app.UseSessionActivityTracking();
To ensure session timeout detection works accurately, you will need to prevent cookie sliding expiration on the polling endpoint.
builder.Services.ConfigureApplicationCookie(options =>
{
options.SlidingExpiration = true;
// ... other settings like LoginPath, ExpireTimeSpan, etc.
options.Events.OnCheckSlidingExpiration = context =>
{
// Don't refresh cookie expiration when polling for session status
if (context.Request.Path.StartsWithSegments(SessionActivityTrackingConstants.RemainingTimeEndpoint))
{
context.ShouldRenew = false;
} else
{
context.ShouldRenew = true;
}
return Task.CompletedTask;
};
});
The standard response schema for the API endpoints is as follows:
{
"Success": "boolean", // Indicates if the request was successful"
"Message": "string", // Optional message
"Data": { } // The actual data payload
}
GET /api/session/remaining-time
{
"Success": true,
"Message": "Remaining session time retrieved",
"Data": {
"RemainingSeconds": 180, // Seconds remaining before session timeout
"IsExpired": false // Indicates if the session has expired
}
}
POST /api/session/refresh-time
{
"Success": true,
"Message": "Remaining session time retrieved",
"Data": {
"RemainingSeconds": 1200, // Seconds remaining before session timeout
"IsExpired": false // Indicates if the session has expired
}
}
MIT
If you find any issues or have suggestions, please open an issue or submit a pull request on GitHub.