ChatGPT解决这个技术问题 Extra ChatGPT

InvalidOperationException:无法解析类型“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务

我开始将我的 asp.net core RC1 项目转换为 RC2,但遇到了现在IHttpContextAccessor无法解决的问题。

为简单起见,我使用 Visual Studio 模板 ASP.NET Core Web Application (.Net Framework) 创建了新的 ASP.NET RC2 项目。比我为 HomeController 添加了为我创建的模板的构造函数。

public HomeController(IHttpContextAccessor accessor)
{
}

在我启动应用程序后,我收到下一个错误:

InvalidOperationException:尝试激活“TestNewCore.Controllers.HomeController”时无法解析“Microsoft.AspNetCore.Http.IHttpContextAccessor”类型的服务。 в Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

在我的实际应用程序中,我需要在自己的服务类中解析 IHttpContextAccessor 才能访问 _contextAccessor.HttpContext.Authentication_contextAccessor.HttpContext.User。 Everthing 在 RC1 中运行良好。那么它怎么可能在 RC2 中呢?

此问题已在此处的 aspnet GitHub 存储库中讨论:github.com/aspnet/Hosting/issues/793

J
Joe Audette

IHttpContextAccessor 默认不再绑定,需要自己注册

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

它是有效的。 services.AddScoped<IActionContextAccessor, ActionContextAccessor>() 也有同样的故事
我们有关于适当范围的官方建议吗?应该是 SingletonScoped 还是 Transient
啊,这里讨论过,多人验证它可以安全地是Singletongithub.com/aspnet/Hosting/issues/793
这样做时,我收到此错误:InvalidOperationException: Cannot consume scoped service。任何想法 ?
请参阅有关使用 Microsoft 首选/推荐的提供的扩展方法 services.AddHttpContextAccessor() 的下一个答案。
S
SpruceMoose

从 .NET Core 2.1 开始,添加了一个扩展方法以将 IHttpContextAccessor 正确注册为单例。请参阅Add helper to register IHttpContextAccessor #947。只需在您的 ConfigureServices() 方法中添加以下内容:

services.AddHttpContextAccessor();

这相当于:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

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

虽然此代码可能会解决问题,但including an explanation如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的回答以添加解释并说明适用的限制和假设。