范围服务:访问没有 IHttpContextAccessor 的 HTTP 上下文

Seb*_*zzz 1 asp.net-core

在 ASP.NET Core 中,我有一个在 DI 中注册为作用域的服务。我可以访问该服务中的 HTTP 上下文而不使用IHttpContextAccessor它的开销吗?

dav*_*owl 5

您必须向容器添加一个范围服务,然后您必须添加一个解析该服务的中间件并在其上设置当前的 http 上下文。

public class ScopedHttpContext
{
    public HttpContext HttpContext { get; set; }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<ScopedHttpContext>();
}

public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<ScopedHttpContextMiddleware>();
}

public class ScopedHttpContextMiddleware 
{
    private readonly RequestDelegate _next;

    public ScopedHttpContextMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task InvokeAsync(HttpContext context, ScopedHttpContext scopedContext)
    {
        scopedContext.HttpContext = context;
        return _next(context);
    }
}
Run Code Online (Sandbox Code Playgroud)