I'm trying to do a visitor counter per page, I create an attribute which is call when the page is loaded. After I increment the counter of the page.
But the problem is that I would like specifie an id in the database corresponding to a page respecting the rule of DRY.
Here's the attribute code:
public class PageCounterAttribute : Attribute
{
public PageCounterAttribute(string name, MyDbContext context)
{
Console.WriteLine(name);
DateTime toDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
context.Visits.Add(new Visits()
{
Count = 1,
Date = toDay,
Page = AnId
}) ;
}
}
I have this middleware which count unique visitors.
private readonly RequestDelegate _requestDelegate;
public VisitorsCounter(RequestDelegate requestDelegate)
{
_requestDelegate = requestDelegate;
}
public async Task InvokeAsync(HttpContext context, MyDbContext dbContext)
{
var path = context.Request.Path.Value.ToLower();
if(context.Request.Method == "GET" && !path.Contains('.'))
{
var now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
var newCount = dbContext.Visits.FirstOrDefault(item => item.Date == now);
if (newCount != null)
{
newCount.Count++;
dbContext.Visits.Update(newCount);
}
else
{
dbContext.Visits.Add(new Visits()
{
Count = 1,
Date = now,
Page = 0
});
}
dbContext.SaveChanges();
context.Response.Cookies.Append("VisitorId", Guid.NewGuid().ToString(), new CookieOptions()
{
Path = "/",
HttpOnly = true,
Secure = false,
});
}
await _requestDelegate(context);
}
Thank you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…