روشی برای محاسبهی تعداد کاربران آنلاین در ASP.NET Core
نویسنده: داود میرزایی
تاریخ: ۱۴۰۰/۰۶/۲۹ ۱۷:۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class OnlineUserMiddleWare
{
private readonly RequestDelegate _next;
private readonly IMemoryCache _memoryCache;
public OnlineUserMiddleWare(RequestDelegate next, IMemoryCache memoryCache)
{
_next = next;
_memoryCache = memoryCache;
}
public async Task Invoke(HttpContext context)
{
if (!_memoryCache.TryGetValue("OnlineUsers", out Dictionary<string,DateTime> onlineUsers))
{
onlineUsers = new Dictionary<string, DateTime>();
_memoryCache.Set("OnlineUsers", onlineUsers);
}
if (context.User.Identity.IsAuthenticated)
{
var name = context.User.Identity.Name;
if (name != null)
{
if (onlineUsers.ContainsKey(name))
onlineUsers[name] = DateTime.Now;
else
onlineUsers.Add(name, DateTime.Now);
}
}
foreach (var online in onlineUsers)
{
if (online.Value < DateTime.Now.AddMinutes(-10))
onlineUsers.Remove(online.Key);
}
await _next(context);
}
} public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
...
app.UseMiddleware<OnlineUserMiddleWare>();
...
} public class DashboardController
{
private readonly IMemoryCache _memoryCache;
public DashboardController(memoryCache)
{
_memoryCache = memoryCache;
}
public IActionResult Index()
{
_memoryCache.TryGetValue("OnlineUsers", out Dictionary<string, DateTime> onlineUsers);
ViewBag.OnlineUsers = onlineUsers.Count;
return View();
}
} if(context.Request.Path.StartsWithSegments("/Identity/Account/Login"))
{
foreach (var online in onlineUsers)
{
if (online.Value < DateTime.Now.AddMinutes(-10))
onlineUsers.Remove(online.Key);
}
}
public async Task Invoke(HttpContext context)
{
if (!_memoryCache.TryGetValue("OnlineUsers", out Dictionary<string,DateTime> onlineUsers))
{
onlineUsers = new Dictionary<string, DateTime>();
_memoryCache.Set("OnlineUsers", onlineUsers , new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
}
if (context.User.Identity.IsAuthenticated)
{
var name = context.User.Identity.Name;
if (name != null)
{
if (onlineUsers.ContainsKey(name))
onlineUsers[name] = DateTime.Now;
else
onlineUsers.Add(name, DateTime.Now);
}
}
await _next(context);
}