如何在MVC 4中查询当前登录用户的AD信息

anI*_*Mer 4 asp.net active-directory

我有一个MVC4内部网页,并希望homeDirectory从Active Directory 获取该属性.想知道从AD获取属性的最快方法.

mar*_*c_s 5

由于您使用的是.NET 3.5及更高版本,因此您应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间.在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松查找AD中的用户和/或组:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

   if(user != null)
   {
      // do something here....      
      string homeDrive = user.HomeDrive;
      string homeDirectory = user.HomeDirectory;
   }
}
Run Code Online (Sandbox Code Playgroud)

如果您在ASP.NET MVC应用程序中使用Windows身份验证,则还可以获取当前登录的用户,如下所示:

UserPrincipal currentUser = UserPrincipal.Current;
Run Code Online (Sandbox Code Playgroud)

但更多的,往往不是在一个Web应用程序,这是一样的东西NETWORK SERVICE或者IUSER_machineName用户(而不是你的用户在浏览器)...

新的S.DS.AM使得在AD中与用户和群组玩游戏变得非常容易!