Accessing a Session object from Razor _Layout.cshm

2019-01-11 07:11发布

问题:

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.

I have a CurrentUser object stored in Session scope

回答1:

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


回答2:

An easier way to do it is using Session property directly from the view (HttpContext.Current. prefix should not be necessary at all):

@(CurrentUser)Session["CurrentUser"]