从 Razor _Layout.cshml 访问 Session 对象 [英] Accessing a Session object from Razor _Layout.cshml

查看:16
本文介绍了从 Razor _Layout.cshml 访问 Session 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆