从 Razor _Layout.cshml 访问 Session 对象 [英] Accessing a Session object from Razor _Layout.cshml
问题描述
使用 Razor 构建 MVC 3 应用程序,我在 Session 范围中保留了一些信息,这些信息将在 _Layout 文件中使用.
Building an MVC 3 app with Razor and I have some information persisted in the Session scope that will be used in the _Layout file.
我不知道实现这一点的最佳方法是什么.其中一些信息用于确定标题中呈现的内容.
I have no clue as to what is the best way to implement this. Some of this information is used to determine what is rendered in the header.
我在会话范围内存储了一个 CurrentUser 对象
I have a CurrentUser object stored in Session scope
推荐答案
你可以直接访问布局文件中的 HttpContext
You could just access the HttpContext in the layout file
@HttpContext.Current.Session["Whatever"].ToString()
或者,如果你想访问用户对象,你可以在页面中创建一个对象并分配它
or, if you want access to the user object you could just create an object in the page and assign it
@{ CurrentUser user = (CurrentUser)HttpContext.Current.Session["CurrentUser"]; }
然后在你的代码中......
Then later in your code...
@user.Name
这篇关于从 Razor _Layout.cshml 访问 Session 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!