asp.net-mvc - ASP.NET Core MVC 应用程序中的总命中/访问者计数器

标签 asp.net-mvc asp.net-core asp.net-core-mvc asp.net-core-2.0

我想计算我的 ASP.NET Core Web 应用程序中的点击/访问者总数。每当有新访问者访问我的网站时,数据库中的访问者总值(value)将增加 1。

对于传统的 ASP.NET MVC 应用程序,我们可以通过在 global.asax 文件中的 Session_Star() 方法中使用 Session 变量来解决问题。

在 ASP.NET Core MVC 中这样做的最佳选择是什么?或者我如何跟踪新访问者何时访问我的网站?

任何适当的解决方案将不胜感激。谢谢!

最佳答案

好的!我已经使用 ASP.NET Core Middleware 和 session 解决了这个问题,如下所示:

这是中间件组件:

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);
    }
}

最后在 Startup.cs 文件中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.UseMiddleware(typeof(VisitorCounterMiddleware));
}

关于asp.net-mvc - ASP.NET Core MVC 应用程序中的总命中/访问者计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49798923/

相关文章:

asp.net-core - Microsoft.AspNet.Identity vnext 中的 UserValidator

c# - 将 header 添加到操作请求和响应

asp.net-mvc - 我应该如何保护我的 SPA 和 Web.API?

c# 依赖注入(inject)无法将 lambda 转换为预期的委托(delegate)

asp.net-core - 为什么 Giraffe/AspNetCore + SignalR 依赖注入(inject)无法解析 MailboxProcessor 单例?

c# - AuthorizationHandler 和数据库依赖注入(inject)

c# - 实现依赖注入(inject)静态方法

c# - 格式化要显示的 ajax.actionlink 文本

c# - 在ASP.NET Core 3.0 Swagger中将字符串标记为不可为空

c# - 如何使用标准 MVC Core 依赖注入(inject)解决未注册的类型