[英]How do you access HttpContext from within _Layout.cshtml
Project: ASP.NET Core 7 MVC web application项目:ASP.NET Core 7 MVC web 应用
I've added an object to the HttpContext.Items
collection from within a controller and I am trying to access the object to hide some menu options in the _Layout.cshtml
, but I am getting an error我已将 object 添加到 controller 中的
HttpContext.Items
集合中,我正在尝试访问 object 以隐藏_Layout.cshtml
中的一些菜单选项,但出现错误
Object reference required
Object 需要参考
How do I set the reference?如何设置参考?
@if (HttpContext.Items["CurrentUser"] == null) { }
It seems that you are calling HttpContext as static like:您似乎将 HttpContext 称为 static,例如:
you could get the instance of HttpContext in View as below:您可以在 View 中获取 HttpContext 的实例,如下所示:
this.ViewContext.HttpContext
althougth you could get the httpcontext,It would also not work for your requirement.虽然您可以获得 httpcontext,但它也不能满足您的要求。
You'd better try with ViewData/ViewBag您最好尝试使用 ViewData/ViewBag
In Controller:在 Controller:
ViewData["Key"]=somevalue
In View:在视图中:
@if(ViewData["Key"]==null){....}
Access the RazorPage
Context
property:访问
RazorPage
Context
属性:
@if (Context.Items["CurrentUser"] == null) { }
I injected the reference @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor我注入了引用@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.