InvalidOperationException:无法解析类型为“ Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务 [英] InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'

查看:855
本文介绍了InvalidOperationException:无法解析类型为“ Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

为简单起见,我使用Visual Studio模板 ASP.NET Core Web应用程序(.Net Framework)创建了一个新的ASP.NET RC2项目。

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:尝试激活 TestNewCore.Controllers.HomeController时,无法解析类型为 Microsoft.AspNetCore.Http.IHttpContextAccessor的服务。
•Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired)

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)

在我的实际应用程序中,我需要在我自己的服务类中解析 IHttpContextAccessor ,以访问 _contextAccessor.HttpContext.Authentication ,到 _contextAccessor.HttpContext.User 。 RC1中的Everething效果很好。

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?

推荐答案

默认情况下,IHttpContextAccessor不再处于连线状态,所以您必须自己进行注册

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

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

这篇关于InvalidOperationException:无法解析类型为“ Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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