【问题标题】:Scoped service: Access HTTP context without IHttpContextAccessor作用域服务:在没有 IHttpContextAccessor 的情况下访问 HTTP 上下文
【发布时间】:2018-04-22 14:09:19
【问题描述】:

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

【问题讨论】:

  • overhead 是什么?

标签: asp.net-core


【解决方案1】:

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

【讨论】:

  • 这是朝着正确方向迈出的一步,大卫!直接构造函数注入是不可能的吗?我不会提前知道我是否需要这项服务。
  • 不确定您的意思?这是首先准备 ScopedHttpContext 的应对措施。一旦你这样做了,你可以将 ScopedHttpContext 注入到作用域服务的构造函数中(假设它在你解析之前被设置)
  • 嗨@davidfowl,我使用了与您在回答中建议的方法类似的方法。在我的项目中。但随后我需要确保所有使用此对象的类都必须限定范围。当我需要执行 Task.Run 并且作用域类被释放但使用它们的后台逻辑继续运行时,这会导致问题。对此有任何建议。
  • 在支持 IMiddleware 的 ASP.NET Core 版本中是可能的。
猜你喜欢
  • 2012-07-01
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
  • 2023-03-13
  • 2018-10-02
  • 1970-01-01
相关资源
最近更新 更多