如何在asp.net Windows身份验证中获取用户详细信息

Jee*_*att 11 asp.net

我正在使用Windows身份验证和访问用户名.

IIdentity winId = HttpContext.Current.User.Identity;
string name = winId.Name;
Run Code Online (Sandbox Code Playgroud)

但我想获得其他详细信息,如用户全名和EmailID.

Pre*_*gha 14

由于您在Windows网络上,因此您需要查询Active目录以搜索用户,然后获取其属性,例如电子邮件

这是一个示例函数DisplayUser,IIdentity在Windows认证的网络上给出,找到用户的email:

public static void Main() {
    DisplayUser(WindowsIdentity.GetCurrent());
    Console.ReadKey();    
}

public static void DisplayUser(IIdentity id) {    
    WindowsIdentity winId = id as WindowsIdentity;
    if (id == null) {
        Console.WriteLine("Identity is not a windows identity");
        return;
    }

    string userInQuestion = winId.Name.Split('\\')[1];
    string myDomain = winId.Name.Split('\\')[0]; // this is the domain that the user is in
     // the account that this program runs in should be authenticated in there                    
    DirectoryEntry entry = new DirectoryEntry("LDAP://" + myDomain);
    DirectorySearcher adSearcher = new DirectorySearcher(entry);

    adSearcher.SearchScope = SearchScope.Subtree;
    adSearcher.Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))";
    SearchResult userObject = adSearcher.FindOne();
    if (userObject != null) {
        string[] props = new string[] { "title", "mail" };
        foreach (string prop in props) {
            Console.WriteLine("{0} : {1}", prop, userObject.Properties[prop][0]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

给出这个: 替代文字

编辑:如果您收到"错误的用户/密码错误" 代码运行的帐户必须访问用户域.如果您在asp.net中运行代码,那么Web应用程序必须在具有域访问权限的应用程序池下运行.有关更多信息,请参见此处