Tan*_*jel 5 asp.net-mvc asp.net-core-mvc asp.net-core asp.net-core-2.0
我想计算我的 ASP.NET Core Web 应用程序中的命中/访问者总数。每当有新访问者访问我的网站时,数据库中的访问者总价值将增加 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);
}
}
Run Code Online (Sandbox Code Playgroud)
最后在 Startup.cs 文件中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware(typeof(VisitorCounterMiddleware));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6966 次 |
| 最近记录: |