C# 从Active Directory检索用户名

C# 从Active Directory检索用户名,c#,asp.net,active-directory,iprincipal,C#,Asp.net,Active Directory,Iprincipal,我正在尝试从Active Directory检索用户名。我发现这段代码需要尝试,但是它无法识别User.Identity.Name中的User部分。我已经看了看是否需要添加另一个引用或程序集,但是我没有看到任何东西。有没有更好的方法从Active Directory获取用户名 static string GetUserName(){ string name = ""; using (var context = new PrincipalContext(Conte

我正在尝试从Active Directory检索用户名。我发现这段代码需要尝试,但是它无法识别
User.Identity.Name
中的
User
部分。我已经看了看是否需要添加另一个引用或程序集,但是我没有看到任何东西。有没有更好的方法从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;
        }

    }

您可以使用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();
很高兴帮助你

那么:

public string GetUserName()
{
    string name = "";

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        var usr = UserPrincipal.Current;

        if (usr != null)
        {
            name = usr.DisplayName;
        }
    }
}

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