.NET Core IHttpContextAccessor issue

柔情痞子 提交于 2019-12-24 02:16:52

问题


I have static helper class

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

How I can get access to current HttpContext inside Host property?


回答1:


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.

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;
    }
}

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.

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

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

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.

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

Source: The IHttpContextAccessor service is not registered by default



来源:https://stackoverflow.com/questions/40303982/net-core-ihttpcontextaccessor-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!