简体   繁体   English

如何从 _Layout.cshtml 访问 HttpContext

[英]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.

相关问题 如何将数据库中的数据添加到 ASP.NET Core MVC (.NET 6) 应用程序中的共享 _Layout.cshtml? - How do you add data from the database to the shared _Layout.cshtml in ASP.NET Core MVC (.NET 6) application? 如何将数组从控制器传递到_layout.cshtml - How to pass an array from controller to _layout.cshtml 如何将路径参数注入_Layout.cshtml - How to inject a route parameter into _Layout.cshtml 在 layout.cshtml 中实现多个部分 - Implement multiple section in layout.cshtml ASP.NET Core MVC 中 Layout.cshtml 中的访问请求或 IQueryCollection? - Access Request or IQueryCollection in Layout.cshtml in ASP.NET Core MVC? 无法找到布局视图“~/Views/Shared/_Layout.cshtml” - The layout view '~/Views/Shared/_Layout.cshtml' could not be located _layout.cshtml 在 /Home/Index 时看不到 object - _layout.cshtml not seeing object when at /Home/Index 将数据发送到_Layout.cshtml的标头,无论用户位于哪个页面上 - Sending data to header of _Layout.cshtml regardless of what page the user is on 在 MVC Core _Layout.cshtml 中访问选定的请求本地化文化 - accessing selected request localization culture in MVC Core _Layout.cshtml 当我尝试编辑 _layout.cshtml 文件时,Visual Studio 2022 挂起,它可以与其他 cshtml 文件一起编辑 - visual studio 2022 gets hang when i try to edit _layout.cshtml file, its ok with other cshtml files edit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM