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

时间:2018-04-22 14:09:19

标签: asp.net-core

在ASP.NET Core中,我有一个在DI中注册为scoped的服务。我是否可以使用IHttpContextAccessor访问该服务中的HTTP上下文而不是及其拥有的开销?

1 个答案:

答案 0 :(得分:3)

您必须向容器添加范围内的服务,然后您必须添加一个解决该服务的中间件并在其上设置当前的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);
    }
}