c# - 从 Active Directory 检索用户名

标签 c# asp.net active-directory iprincipal

我正在尝试从 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;
        }

    }

最佳答案

您可以使用 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();

很高兴为您服务!

关于c# - 从 Active Directory 检索用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40771469/

相关文章:

c# - LINQ 中的全词搜索

c# - AsyncCallback 通过引用变量取值

asp.net - 重定向到 returnUrl 在 Asp.Net MVC5 中如何工作

c# - 如何向ffmpeg提供登录用户名和密码?

azure - 无法通过 Easy Auth 刷新 AD access_token (403)

c# - 在 UWP 应用程序中模拟输入

c# - 为什么在我上次将输出编码保留为 UTF8 时 csc.exe 崩溃?

asp.net - 从 Azure Active Directory 授权用户

azure - 针对 Azure AD 的主动身份验证

C# - 在事件目录中查找用户管理器