且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 MVC6 中正确注入 HttpContext

更新时间:2023-02-24 11:39:44

如果你试图访问 HttpContext,那么你可以使用 IHttpContextAccessor 来达到这个目的.

If you are trying to access HttpContext, then you can use IHttpContextAccessor for this purpose.

例子:

services.AddTransient<QueryValueService>();

public class QueryValueService
{
    private readonly IHttpContextAccessor _accessor;

    public QueryValueService(IHttpContextAccessor httpContextAccessor)
    {
        _accessor = httpContextAccessor;
    }

    public string GetValue()
    {
        return _accessor.HttpContext.Request.Query["value"];
    }
}

请注意,在上面的示例中,QueryValueService 应仅注册为 TransientScoped 而不是 SingletonHttpContext 是基于每个请求的...

Note that in the above example QueryValueService should be registered only as Transient or Scoped and not Singleton as HttpContext is per-request based...