如何使用中间件和 ASP.NET 核心计算总观看次数

How to count total views using Middleware and ASP.NET Core

假设我有 aaaa.com/Class,如果用户导航到这个 link,我希望我的数据库中的 PageCount 递增 1。请帮助我。

您可以通过以下方式获取中间件中的url:

using Microsoft.AspNetCore.Http.Extensions;

public class MyMiddleware
{
    private readonly RequestDelegate _next;
    
    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext, ApplicationDbContext _context)
    {
        //get the url
        var url = httpContext.Request.GetDisplayUrl();
        if(url== "your link url")
        {
            //find your data
            var p = _context.Page.Find(1);
            p.PageCount++;
            _context.Update(p);
            _context.SaveChanges();
        }
        await _next(httpContext);
    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions
{
    public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyMiddleware>();
    }
}