使用布局页面使变量在所有视图上可用

时间:2019-07-19 14:47:00

标签: asp.net-mvc

我在家庭控制器索引页面上具有以下代码,以获取一些AD信息。具体来说,我在布局页面中使用@Session [“ Username”]。我的问题是,是否可以在布局页面中使用以下代码,以便无论有人打开哪个视图,这些会话始终可用?这对我需要的东西有意义吗?

谢谢, EB

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;
        if (directoryEntry.Properties.Contains("Department"))
            Session["Department"] =  directoryEntry.Properties["department"].Value.ToString();
        if (directoryEntry.Properties.Contains("Office"))
            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);
}

0 个答案:

没有答案