核心 MVC 应用程序中 ASP.NET 总点击/访客计数器



我想计算我的 ASP.NET 核心Web应用程序中的总点击量/访问者总数。每当有新访问者访问我的网站时,数据库中的总访问者价值将增加一个。

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

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

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

好的!我已经使用 ASP.NET 核心中间件和会话解决了这个问题,如下所示:

下面是中间件组件:

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

最后在启动.cs文件中:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.UseMiddleware(typeof(VisitorCounterMiddleware));
}
这是我

的解决方案(ASP.Net Core 2.2 MVC(;

首先,您需要捕获访问者的远程IP。为此,请将以下代码放入启动配置服务方法:

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

然后在您的默认端点(我的是主页/索引(中,使用以下方法获取访问者的 IP:

string remoteIpAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            if (Request.Headers.ContainsKey("X-Forwarded-For"))
            { 
                remoteIpAddress = Request.Headers["X-Forwarded-For"];
            }

获取远程 IP 后,如果这是第一次访问,您可以将其保存到数据库中。您可以为此创建一个简单的模型,就像我的一样:

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

如果这不是客户的第一次访问,那么只需增加CountOfVisit属性值即可。您必须在客户端对默认端点的第一个请求时执行所有这些操作。避免配音。

最后,您可以编写符合您需求的自定义方法。

最新更新