We're following this official ASP.NET document: 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 that is called from corresponding View. But we are getting HttpContext.Items[...]
as null inside ViewComponent
.
Controller:
HttpContext.Items["TestVal"]= "some value";
View:
@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);
}
}
UPDATE:
In Controller section above, changed Http.Items
to HttpContext.Items
in the line at: HttpContext.Items["TestVal"]= "some value";
Final update:
I've tested simple case like as in your example, and this works well (on MVC Core v1.1.0).
So, it's hard to say why it's not working in your particular case.
However following our discussion in comments, you've found a source of the problem:
Orginal answer:
In the documentation you could read:
and in section Working with HttpContext.Items:
and in View Components documentation: