Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework core 如何使用中间件和ASP.NET核心计算总视图_Entity Framework Core_Asp.net Core Mvc_Middleware - Fatal编程技术网

Entity framework core 如何使用中间件和ASP.NET核心计算总视图

Entity framework core 如何使用中间件和ASP.NET核心计算总视图,entity-framework-core,asp.net-core-mvc,middleware,Entity Framework Core,Asp.net Core Mvc,Middleware,假设我有aaaa.com/Class,如果用户导航到此链接,我希望数据库中的PageCount增加1。请帮助我。您可以通过以下方式获取中间件中的url: using Microsoft.AspNetCore.Http.Extensions; public class MyMiddleware { private readonly RequestDelegate _next; public MyMiddleware(RequestDelegate next) {

假设我有
aaaa.com/Class
,如果用户导航到此链接,我希望数据库中的
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>();
    }
}
使用Microsoft.AspNetCore.Http.Extensions;
公共类中间件
{
private readonly RequestDelegate\u next;
公共MyMiddleware(RequestDelegate下一步)
{
_下一个=下一个;
}
公共异步任务调用(HttpContext HttpContext、ApplicationDbContext\u context)
{
//获取url
var url=httpContext.Request.GetDisplayUrl();
如果(url==“您的链接url”)
{
//查找您的数据
var p=_context.Page.Find(1);
p、 PageCount++;
_更新(p);
_SaveChanges();
}
等待下一步(httpContext);
}
}
//用于将中间件添加到HTTP请求管道的扩展方法。
公共静态类MyMiddlewareExtensions
{
公共静态IAApplicationBuilder UseMyMiddleware(此IAApplicationBuilder)
{
返回builder.UseMiddleware();
}
}

Hi@destinyidika,有关于这个案例的最新消息吗?感谢兄弟的快速响应,我已经尝试了上述实现,如果我能找出解决它所遇到的错误的方法,它似乎刚刚开始工作。错误为{无法从根提供程序解析作用域服务“MVC\u已访问数.ApplicationDBContext”。}。如果您能帮助解决此问题,我们将不胜感激。再次感谢兄弟