从 ViewComponent returns 访问 HttpContext.Items NULL

Accessing HttpContext.Items from ViewComponent returns NULL

我们正在关注此官方 ASP.NET 文档:Managing Application State. In our one we controller we're setting a value for HttpContext.Items[...] and are trying to access that value from a ViewComponent 从相应的视图调用。但是我们在 ViewComponent.

中将 HttpContext.Items[...] 设为 null

控制器:

HttpContext.Items["TestVal"]= "some value";

查看:

@await Component.InvokeAsync("myVC")

ViewComponent:

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";

最终更新:

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

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

然而,在我们在评论中进行讨论后,您找到了问题的根源:

I realised the issue is not related to ViewComponent; it's rather related to scope of HttpContext


原回答:

在文档中您可以阅读:

Its contents are discarded after each request. It is best used as a means of communicating between components or middleware that operate at different points in time during a request

Working with HttpContext.Items 部分:

This collection is available from the start of an HttpRequest and is discarded at the end of each request.

并在 View Components documentation 中:

Are overloaded on the signature rather than any details of the current HTTP request

HttpContext.Current 在 ASP.NET Core 中是不可能的。从单独的 class 库访问当前 HTTP 上下文是 ASP.NET Core 试图避免的那种混乱架构。

但是可以使用 ASP.NET 核心依赖注入系统中的 IHttpContextAccessor 获取上下文:

public class SomeClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;

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

HttpContextAccessor 被注入时,你可以做类似的事情:var context = _httpContextAccessor.HttpContext;.