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

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

问题描述

我开始将我的 asp.net core 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 Application (.Net Framework) 创建了新的 ASP.NET RC2 项目.比我为 HomeController 添加了构造函数,它为我创建了模板.

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.Everething 在 RC1 中运行良好.那么它怎么可能会出现在 RC2 中呢?

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天全站免登陆