【问题标题】:Retrieving User Name from Active Directory从 Active Directory 检索用户名
【发布时间】:2017-04-07 21:01:40
【问题描述】:

我正在尝试从 Active Directory 中检索用户名。我发现这段代码可以尝试,但是它不能识别User.Identity.NameUser 部分。我已经查看是否需要添加另一个引用或程序集,但是我没有看到任何东西。有没有更好的方法从 Active Directory 中获取用户名?

static string GetUserName(){

        string name = "";
        using (var context = new PrincipalContext(ContextType.Domain))
        {
            var usr = UserPrincipal.FindByIdentity(context, User.Identity.Name);
            if (usr != null)
                name = usr.DisplayName;
        }

    }

【问题讨论】:

    标签: c# asp.net active-directory iprincipal


    【解决方案1】:

    您可以使用 WindowsIdentity.GetCurrent

    using System.Security.Principal;
    
    static string GetUserName()
    {
        WindowsIdentity wi = WindowsIdentity.GetCurrent();
    
        string[] parts = wi.Name.Split('\\');
    
        if(parts.Length > 1) //If you are under a domain
            return parts[1];
        else
            return wi.Name;
    }
    

    用法:

    string fullName = GetUserName();
    

    很高兴为您提供帮助!

    【讨论】:

    • 由于某种原因,当我尝试此操作时,wi.Name.Split 中的 wi 无法识别
    • 您是否引用“使用 System.Security.Principal;”?
    • 是的,我参考了它。它说 - 字段初始值设定项不能引用非静态字段、方法或属性“OpenBurn.Controllers.RequestBurnsController.wi”
    • 请发布您的整个课程。错误在另一个代码点上。
    • 如何调用 GetUserName() 以在我的控制器中获取 wi.Name?
    【解决方案2】:

    怎么样:

    public string GetUserName()
    {
        string name = "";
    
        using (var context = new PrincipalContext(ContextType.Domain))
        {
            var usr = UserPrincipal.Current;
    
            if (usr != null)
            {
                name = usr.DisplayName;
            }
        }
    }
    

    【讨论】: