ChatGPT解决这个技术问题 Extra ChatGPT

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'

I started to convert my asp.net core RC1 project to RC2 and faced with problem that now IHttpContextAccessordoes not resolved.

For sake of simplicity I created new ASP.NET RC2 project using Visual Studio Template ASP.NET Core Web Application (.Net Framework). Than I added constructor for HomeController which template created for me.

public HomeController(IHttpContextAccessor accessor)
{
}

And after I start application I receive next error:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'TestNewCore.Controllers.HomeController'. в Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

In my real application I need to resolve IHttpContextAccessor in my own service class for getting access to _contextAccessor.HttpContext.Authentication and to _contextAccessor.HttpContext.User. Everething works fine in RC1. So how can it suppose to be in RC2?

This issue has been discussed on the aspnet GitHub repository here: github.com/aspnet/Hosting/issues/793

J
Joe Audette

IHttpContextAccessor is no longer wired up by default, you have to register it yourself

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

It is worked. Also same story with services.AddScoped<IActionContextAccessor, ActionContextAccessor>()
Do we have an official recommendation about what the proper scope is? Should it be Singleton, Scoped or Transient?
Ah it's discussed here, and multiple people verifies it can safely be Singleton. github.com/aspnet/Hosting/issues/793
When doing that, I got this error : InvalidOperationException: Cannot consume scoped service. Any idea ?
Please see the next answer about using the provided extension method services.AddHttpContextAccessor() which is preferred/recommended by Microsoft.
S
SpruceMoose

As of .NET Core 2.1 there is an extension method that has been added to correctly register an IHttpContextAccessor as a singleton. See Add helper to register IHttpContextAccessor #947. Simply add as follows in your ConfigureServices() method:

services.AddHttpContextAccessor();

This is equivalent to:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

S
Suraj Rao
services.AddScoped(sp => sp.GetService<IHttpContextAccessor>().HttpContext.Session);

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.