【问题标题】:Accessing HttpContext.Items from ViewComponent returns NULL从 ViewComponent 访问 HttpContext.Items 返回 NULL
【发布时间】:2017-01-08 00:47:39
【问题描述】:

我们正在关注这个 ASP.NET 官方文档:Managing Application State。在我们的控制器中,我们正在为HttpContext.Items[...] 设置一个值,并尝试从相应视图调用的ViewComponent 访问该值。但是我们在ViewComponent 中将HttpContext.Items[...] 设为null。

控制器:

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);
    }
}

更新

在上面的控制器部分中,将 Http.Items 更改为 HttpContext.Items 在以下行中:HttpContext.Items["TestVal"]= "some value";

【问题讨论】:

    标签: c# asp.net-core asp.net-core-viewcomponent


    【解决方案1】:

    最终更新:

    我已经测试了像您的示例一样的简单案例,并且效果很好(在 MVC Core v1.1.0 上)。

    因此,很难说为什么它在您的特定情况下不起作用。

    但是在我们在 cmets 中的讨论之后,您已经找到了问题的根源:

    我意识到这个问题与 ViewComponent 无关;它与HttpContext的范围有关


    原始答案:

    在您可以阅读的文档中:

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

    Working with HttpContext.Items部分:

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

    View Components documentation:

    重载于签名而不是当前HTTP请求的任何细节

    【讨论】:

    • 我已经删除了我原来的答案,因为我错了 - 请找到我的更新。
    • 根据您的要求,我已取消标记。而且,是的,在代码中我使用了HttpContext.Items 而不是Http.Items。我也更新了我的帖子。
    • 该问题与您在原始回复中指出的内容有关:Its contents are discarded after each request。我所做的是我有一个左导航菜单,该菜单通过另一个控制器通过另一个 ViewComponent 填充。当用户单击左侧菜单上的链接时,它会调用另一个控制器中的另一个操作,该控制器将信息发送到其视图,该视图反过来又调用另一个 ViewComponent。在您向我指出引用文档中的引号后,我意识到该问题与 ViewComponent 无关;它与 HttpContext 的范围有关
    • 谢谢你的解释,它可能对其他开发者有帮助。
    • 由于我的原始答案很有帮助,我已经恢复了我的那部分有用的部分。我希望这现在有意义。
    【解决方案2】:

    在 ASP.NET Core 中无法获取 HttpContext.Current。从单独的类库访问当前的 HTTP 上下文是 ASP.NET Core 试图避免的那种混乱架构。

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

    public class SomeClass
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
    
        public SomeClass(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    }
    

    HttpContextAccessor 将被注入时,您可以执行以下操作:var context = _httpContextAccessor.HttpContext;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多