Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

c# - Asp net core razor page assign id


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...