gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:57:34 25 4
gpt4 key购买 nike

我想计算我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com