Last post Jul 23, 2019 08:46 AM by Yongqing Yu
Jul 22, 2019 02:52 PM|Baze72|LINK
I have the code below on my Home Controller Index page to get some AD information. Specifically I am using @Session["Username"] in my layout page. My question is, is it possible to use the following code in the layout page so that regardless of what view
someone opens those sessions are always available? Does that make sense what I am needing?
using (var context = new PrincipalContext(ContextType.Domain, "DOMAIN.local"))
var user = UserPrincipal.FindByIdentity(context, username);
DirectoryEntry directoryEntry = user.GetUnderlyingObject() as DirectoryEntry;
if (user != null)
Session["UserName"] = user.Name;
Session["EmailAddress"] = user.EmailAddress;
Session["Department"] = directoryEntry.Properties["department"].Value.ToString();
Session["Office"] = directoryEntry.Properties["Office"].Value.ToString();
// find the group in question
UserPrincipal usr = UserPrincipal.FindByIdentity(context, User.Identity.Name);
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Users");
Session["Admin"] = usr.IsMemberOf(group);
Jul 22, 2019 03:07 PM|mgebhard|LINK
I would set Session in the Global.asax not the layout view.
Jul 23, 2019 08:46 AM|Yongqing Yu|LINK
is it possible to use the following code in the layout page so that regardless of what view someone opens those sessions are always available?
Yes,it is possible.
But it's important to note that to display the same session content on other pages, you need to open the page that sets the session value first.
I have made a simple example based on your requirements.
In my example,there are two views that refer to the same _layout page.
In first view's controller,I have set Session["User"]="YOY",and do nothing on the second view, then add this sentence in _layout page:
Finally, open two views to see if “ YOY” in red is displayed in each view.