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

编程入门 行业动态 更新时间:2024-10-20 11:35:13
本文介绍了InvalidOperationException:无法解析类型为“ Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I started to convert my asp 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.IHttpContextAccesso

本文发布于:2023-11-17 04:49:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608888.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   Microsoft   InvalidOperationException   IHttpContextAccessor   Http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!