Reputation: 32089
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!
Upvotes: 8
Views: 12587
Reputation: 21
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.
Upvotes: 2
Reputation: 32089
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));
}
Upvotes: 12