How to add IHttpContextAccessor in the Startup class in the DI in ASP.NET Core 1.0?

前端 未结 2 1482
礼貌的吻别
礼貌的吻别 2020-12-01 05:26

In ASP.NET Core RC 1 I used the following code to retrieve the value of context (full address of the page). Then I recorded this value in the configuration.

p         


        
相关标签:
2条回答
  • 2020-12-01 05:54

    You can add in this way.

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    
    0 讨论(0)
  • 2020-12-01 05:58

    It is no longer a default service. You have to configure it in Startup.cs

    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
    

    UPDATE: In ASP.NET Core 2.1, the AddHttpContextAccessor helper extension method was added to correctly register the IHttpContextAccessor with the correct lifetime (singleton). So, in ASP.NET Core 2.1 and above, the code should be

    services.AddHttpContextAccessor();
    services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
    

    Source: https://github.com/aspnet/Hosting/issues/793

    0 讨论(0)
提交回复
热议问题