asp.net-coreasp.net-core-2.2static-sitevisitor-statistic

ASP.NET Core website visitor statistics counter


I need to create a site with ASP.NET Core 2.2 that will show and count the number of visitors to the site in four modes:

In the GitHub repository and other sources, I didn't find anything because it was either related to ASP.NET Core MVC and lower versions, or it was incomplete.

Has anyone made such a code that can help?

Some example by ASP.NET MVC in Global.asax - but I need code for ASP.NET Core:

public static void CounterState()
{
    DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

    if (HttpContext.Current.Request.Cookies["StateSite"] != null)
    {
        if (Convert.ToDateTime(HttpContext.Current.Request.Cookies["StateSite"].Value.ToString()) != dt)
        {
            HttpCookie cookieCode = new HttpCookie("StateSite", dt.ToString());
            HttpContext.Current.Response.Cookies.Add(cookieCode);
            CountUpState();
        }
    }
    else
    {
        CountUpState();
        HttpCookie cookie = new HttpCookie("StateSite");
        cookie.Value = dt.ToString();
        HttpContext.Current.Response.Cookies.Add(cookie);
    }
}

Solution

  • ASP.NET Core 2.2 is an older version; you might consider using the latest version.

    I need to create a site with ASP.NET Core 2.2 that will show and count the number of visitors to the site in four modes:

    People Online Today's Views Month's Views Total Views

    Generally, we will store user information in cookie, so you can create a middleware that will track visitors (get the visitor information from cookie) and store the data in a database or memory cache.

    Refer to the following steps:

    1.Create a service to manage visitor counts.

    using System.Collections.Concurrent;
    
    public class VisitorCounterService
    {
        private readonly ConcurrentDictionary<string, DateTime> _activeUsers = new ConcurrentDictionary<string, DateTime>();
        private int _todayViews = 0;
        private int _monthViews = 0;
        private int _totalViews = 0;
    
        public void RegisterVisit(string userId)
        {
            var now = DateTime.UtcNow;
    
            // Remove inactive users (older than 10 minutes)
            var inactiveUsers = _activeUsers.Where(kvp => (now - kvp.Value).TotalMinutes > 10).ToList();
            foreach (var user in inactiveUsers)
            {
                _activeUsers.TryRemove(user.Key, out _);
            }
    
            // Add or update user activity
            _activeUsers[userId] = now;
    
            // Increment views
            _todayViews++;
            _monthViews++;
            _totalViews++;
        }
    
        public int GetOnlineUsers() => _activeUsers.Count;
        public int GetTodayViews() => _todayViews;
        public int GetMonthViews() => _monthViews;
        public int GetTotalViews() => _totalViews;
    }
    

    2.Create a middleware that will track visitors.

    using Microsoft.AspNetCore.Http;
    
    public class VisitorTrackingMiddleware : IMiddleware
    {
        private readonly VisitorCounterService _visitorService;
    
        public VisitorTrackingMiddleware(VisitorCounterService visitorService)
        {
            _visitorService = visitorService;
        }
    
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            string userId = context.Request.Cookies["VisitorId"];
            if (string.IsNullOrEmpty(userId))
            {
                userId = Guid.NewGuid().ToString();
                context.Response.Cookies.Append("VisitorId", userId, new CookieOptions
                {
                    Expires = DateTime.UtcNow.AddDays(30),
                    HttpOnly = true
                });
            }
    
            _visitorService.RegisterVisit(userId);
            await next(context);
        }
    }
    

    3.Register the service and middleware in Program.cs file: if you are using asp.net core 2.2 version, you need to register the service and middleware in the startup.cs file.

    // Register services
    builder.Services.AddSingleton<VisitorCounterService>();
    builder.Services.AddTransient<VisitorTrackingMiddleware>(); // Middleware as a service
    builder.Services.AddControllersWithViews(); // For MVC support
    
    var app = builder.Build();
    
    // Use middleware
    app.UseMiddleware<VisitorTrackingMiddleware>();
    
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    

    4.Then in the view page, you can display the visitor statistics:

    @inject VisitorCounterService VisitorService
    
    <h3>Visitor Statistics</h3>
    <ul>
        <li><b>People Online:</b> @VisitorService.GetOnlineUsers()</li>
        <li><b>Today's Views:</b> @VisitorService.GetTodayViews()</li>
        <li><b>Month's Views:</b> @VisitorService.GetMonthViews()</li>
        <li><b>Total Views:</b> @VisitorService.GetTotalViews()</li>
    </ul>
    

    Note: In the VisitorCunter service, before increasing the number of views, it is better to check visitor exist to prevent duplicate counter.