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

标签 asp.net active-directory

我有一个 MVC4 内网页面,想获取 homeDirectory来自 Active Directory 的属性。想知道从 AD 获取属性的最快方法。

最佳答案

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

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

  • 基本上,您可以定义域上下文并轻松找到 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;
       }
    }
    

    如果您在 ASP.NET MVC 应用程序中使用 Windows 身份验证,您还可以像这样获取当前登录的用户:
    UserPrincipal currentUser = UserPrincipal.Current;
    

    但通常情况下,在网络应用程序中,这类似于 NETWORK SERVICEIUSER_machineName用户(而不是您在浏览器上的用户)...

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

    关于asp.net - 如何在MVC 4中查询当前登录用户的AD信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13793126/

    相关文章:

    C# DataAnnotations 正则表达式不正确匹配

    asp.net - Url 路径编码最简单的方法?

    C# 事件目录 : Get domain name of user?

    powershell - 从 LastLogonTimestamp 中提取日期

    C# ActiveDirectory,如何将范围添加到过滤器

    c# - 防止 ASP.Net 项目将 {assembly}.dll.config 复制到 bin 文件夹

    c# - 用户控件中的内容

    jquery - gridview 中的下一行 asp.net jquery

    c# - 在不要求凭据的情况下根据事件目录对用户进行身份验证

    c# - 如何查询一个域的用户是否是另一个AD域中的组的成员?