.NET Core IHttpContextAccessor问题 [英] .NET Core IHttpContextAccessor issue

查看:1202
本文介绍了.NET Core IHttpContextAccessor问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有静态帮助程序类

public static class Current
{
    public static string Host
    {
        get { return "httpContextAccessor here"; }
    }
}

如何获取当前的主机属性中的HttpContext?

推荐答案

您不能,也不应该。这完全超出了拥有依赖项注入系统的全部目的。静态类(用于运行时数据或服务定位器)是一种反模式。

You can't and you shouldn't. This beats the whole purpose of having a dependency injection system at all. Static classes (for runtime data or Service Locator) is an anti-pattern.

在ASP.NET Core中,您必须注入 IHttpContextAccessor 在您需要的类中。您可以制作一个非静态类,并按照以下方式进行操作:

In ASP.NET Core you have to inject IHttpContextAccessor in classes where you need it. You can make a non-static class and do something along the lines of:

public class RequestInformation : IRequestInformation
{
    private readonly HttpContext context;

    public RequestInformation(IHttpContextAccessor contextAccessor) 
    {
        // Don't forget null checks
        this.context = contextAccessor.HttpContext;
    }

    public string Host
    {
        get { return this.context./*Do whatever you need here*/; }
    }
}

并在您的类库中将其注入:

and in your class library inject it:

public class SomeClassInClassLibrary
{
    private readonly IRequestInformation requestInfo;

    public SomeClassInClassLibrary(IRequestInfomation requestInfo) 
    {
        // Don't forget null checks
        this.requestInfo = requestInfo;

        // access it
        var host = requestInfo.Host;
    }
}

请注意,您的 SomeClassInClassLibrary 必须使用 Scoped Transient 模式解析,而不能为 Singleton ,因为 HttpContext 仅在请求期间有效。

Be aware that your SomeClassInClassLibrary must be resolved with either Scoped or Transient mode and it can't be Singleton, because HttpContext is only valid for the duration of the request.

或者,如果 SomeClassInClassLibrary 必须是单例,则必须注入工厂并按需解决 IRequestInformation

Alternatively if SomeClassInClassLibrary has to be singleton, you have to inject a factory and resolve the IRequestInformation on demand (i.e. inside an action).

最后但并非最不重要的是,默认情况下未注册 IHttpContextAccessor

Last but not least, IHttpContextAccessor isn't registered by default.


IHttpContextAccessor可用于访问当前线程的HttpContext。但是,保持此状态将带来不小的性能成本,因此已将其从默认服务集中删除。

IHttpContextAccessor can be used to access the HttpContext for the current thread. However, maintaining this state has non-trivial performance costs so it has been removed from the default set of services.

依赖该状态的开发人员可以根据需要添加回该状态:
services.AddSingleton< IHttpContextAccessor,HttpContextAccessor>();

Developers that depend on it can add it back as needed: services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

来源:默认情况下,未注册IHttpContextAccessor服务

这篇关于.NET Core IHttpContextAccessor问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆