C# 从ViewComponent访问HttpContext.Items返回NULL

C# 从ViewComponent访问HttpContext.Items返回NULL,c#,asp.net-core,asp.net-core-viewcomponent,C#,Asp.net Core,Asp.net Core Viewcomponent,我们正在关注此ASP.NET官方文档:。在我们的one-we控制器中,我们正在为HttpContext.Items[…]设置一个值,并试图从相应视图中调用的访问该值。但是我们在ViewComponent中得到的HttpContext.Items[…]为空 控制器: HttpContext.Items["TestVal"]= "some value"; @await Component.InvokeAsync("myVC") 查看:

我们正在关注此ASP.NET官方文档:。在我们的one-we控制器中,我们正在为
HttpContext.Items[…]
设置一个值,并试图从相应视图中调用的访问该值。但是我们在
ViewComponent
中得到的
HttpContext.Items[…]
为空

控制器:

HttpContext.Items["TestVal"]= "some value";
@await Component.InvokeAsync("myVC")
查看:

HttpContext.Items["TestVal"]= "some value";
@await Component.InvokeAsync("myVC")
视图组件

public class myVCViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        String myVal= Http.Items["TestVal"].ToString(); //issue: Http.Items["TestVal"] is null at this line
        return View(items);
    }
}
公共类myVCViewComponent:ViewComponent { 公共异步任务InvokeAsync() { 字符串myVal=Http.Items[“TestVal”].ToString();//问题:Http.Items[“TestVal”]在此行为空 返回视图(项目); } } 更新

public class myVCViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        String myVal= Http.Items["TestVal"].ToString(); //issue: Http.Items["TestVal"] is null at this line
        return View(items);
    }
}

在上面的控制器部分中,将
Http.Items
更改为
HttpContext.Items
行中的
HttpContext.Items[“TestVal”]=“some value”

最终更新:

HttpContext.Items["TestVal"]= "some value";
@await Component.InvokeAsync("myVC")
我已经测试过像您的示例中那样的简单案例,并且效果很好(在MVCCoreV1.1.0上)

所以,很难说为什么它在你的特殊情况下不起作用

然而,根据我们在评论中的讨论,您发现了问题的根源:

我意识到问题与ViewComponent无关;这与HttpContext的范围有很大关系


原始答案:

HttpContext.Items["TestVal"]= "some value";
@await Component.InvokeAsync("myVC")
在文档中,您可以阅读:

它的内容在每次请求后都会被丢弃。它最好用作在请求期间在不同时间点运行的组件或中间件之间的通信手段

在第节中:

此集合在HttpRequest开始时可用,并在每个请求结束时丢弃

以及:

在签名上重载,而不是在当前HTTP请求的任何详细信息上重载


无法在ASP.NET核心中获取HttpContext.Current。从单独的类库访问当前HTTP上下文是ASP.NET Core试图避免的混乱体系结构类型

但是可以使用IHttpContextAccessor从ASP.NET核心依赖项注入系统获取上下文,如下所示:

public class SomeClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public SomeClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
}

HttpContextAccessor
将被注入时,您可以这样做:
var context=\u HttpContextAccessor.HttpContext

我已删除我的原始答案,因为我错了-请查找我的更新。根据您的请求,我已取消标记。是的,在代码中我使用了
HttpContext.Items
而不是
Http.Items
。我也更新了我的帖子。这个问题与您在原始回复中指出的内容有关:
它的内容在每次请求后都会被丢弃。我所做的是,我有一个左侧导航菜单,通过另一个控制器通过另一个ViewComponent填充。当用户单击左侧菜单上的链接时,它将调用另一个控制器中的另一个操作,该控制器将信息发送到其视图,该视图反过来调用另一个ViewComponent。在您向我指出引用文档中的引用之后,我意识到该问题与ViewComponent无关;这与HttpContextThank的范围有关。谢谢你的解释,这可能对其他开发人员有所帮助。因为我最初的回答很有帮助,所以我已经恢复了我的部分内容,这部分内容很有帮助。我希望这现在是有意义的。