Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total hit/visitor counter in ASP.NET Core MVC Application

I would like to count total ever hit/visitor in my ASP.NET Core Web application. Whenever a new visitor will come to my site, total ever visitor value will be increased by one in database.

In case of traditional ASP.NET MVC Application we can solve the problem by using Session variable in Session_Star() method in the global.asax file.

What would be the best option to do so in ASP.NET Core MVC? Or how can I track whenever a new visitor will come to my site?

Any appropriate solution will highly be appreciated. Thanks!

like image 225
TanvirArjel Avatar asked Apr 12 '18 14:04

TanvirArjel


People also ask

How to get the total visitors count of MVC website using application variable?

This article will explain the code to get the total visitors count of Asp.Net MVC website using Application variable. Create an Asp.Net MVC website and write the below code in Global.asax file. In Application_Start () method declare the variable like below code.

How to manage visitor counter on code level?

If you want to manage visitor on code level you need to start visitor counter under Application_Start method in application configuration file after need to increase the counter on every session. For more details follow the link given below.

What are the performance counters supported by ASP NET?

ASP.NET supports the ASP.NET system performance counters listed in the following table. These counters aggregate information from all ASP.NET applications on a Web server computer.

What is the error counter in ASP NET?

This counter is the sum of the Errors During Compilation, Errors During Preprocessing, and Errors During Execution counters. A well-functioning Web server should not generate errors. If errors occur in your ASP.NET Web application, they may skew any throughput results because of very different code paths for error recovery.


2 Answers

Okay! I have solved the problem using ASP.NET Core Middleware and session as below:

Here is the Middleware component:

public class VisitorCounterMiddleware
{
    private readonly RequestDelegate _requestDelegate;

    public VisitorCounterMiddleware(RequestDelegate requestDelegate)
    {
        _requestDelegate = requestDelegate;
    }

    public async Task Invoke(HttpContext context)
    {
      string visitorId = context.Request.Cookies["VisitorId"];
      if (visitorId == null)
      {
         //don the necessary staffs here to save the count by one

         context.Response.Cookies.Append("VisitorId", Guid.NewGuid().ToString(), new CookieOptions()
            {
                    Path = "/",
                    HttpOnly = true,
                    Secure = false,
            });
       }

      await _requestDelegate(context);
    }
}

Finally in the Startup.cs file:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.UseMiddleware(typeof(VisitorCounterMiddleware));
}
like image 153
TanvirArjel Avatar answered Nov 04 '22 21:11

TanvirArjel


Here is my solution (ASP.Net Core 2.2 MVC);

First you need to catch the remote ip of the visitor. To achieve that, put this code to your startup configure services method:

    services.Configure<ForwardedHeadersOptions>(options => options.ForwardedHeaders = 
    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto);

then in your default end point (mine is home/index), get the ip of the visitor with this:

string remoteIpAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

            if (Request.Headers.ContainsKey("X-Forwarded-For"))
            { 
                remoteIpAddress = Request.Headers["X-Forwarded-For"];
            }

After getting the remote ip, you can save it to your database if this is it's first visit. You can create a simple model for that, like mine:

    public class IPAdress:BaseModel
    {
        public string ClientIp { get; set; }
        public int? CountOfVisit { get; set; }
    }

if it is not the first visit of the client, then simply increase the CountOfVisit property value. You have to do all of those at client's first request to your default end point. Avoid dublication.

Finally, you can write custom methods matching your needs.

like image 22
RAMAZAN KIZILKAYA Avatar answered Nov 04 '22 20:11

RAMAZAN KIZILKAYA