登录不同域时获取登录用户的全名 Windows身份验证 C#



在从不同域读取时,我们遇到了无法获取用户全名的问题。

我的用户名是dom1\jsmith,全名是John Smith。当我们在dom1域中部署项目时,我们可以登录并获得用户的全名。当我们在另一个域(dom2(中部署项目时,用户(dom1\jsmith(具有登录权限,可以访问网站,但无法获得全名。

我们尝试了不同的解决方案,但没有成功。

//output: dom1jsmith
User.Identity.Name;
//output: dom1jsmith
string s = System.Security.Principal.WindowsIdentity.GetCurrent().Name; 
//output: dom1jsmith
string sUserName = System.Environment.UserName;  

//output: John Smith in same domain but not able to find identity
using (var context = new PrincipalContext(ContextType.Domain))
{
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
if (principal != null)
var fullName = string.Format("{0} {1}", principal.GivenName, principal.Surname);

将登录域的名称传递到PrincipalContext的构造函数中。因此,拆分您拥有的DOMAINusername,只使用域部分:

var split = User.Identity.Name.Split('\');
using (var context = new PrincipalContext(ContextType.Domain, split[0])) {
...
}

虽然我很惊讶它没有像你那样工作,因为它对我有效,而且我登录到的域与我的计算机所加入的域不同。尽管在我的情况下,这两个域在同一个AD林中。也许你不是这样。

最新更新