从WindowsIdentity获取用户的显示名称

13

我在使用Windows身份验证的ASP.NET应用程序中。

我正在使用HttpContext.Current.User.Identity.Name获取当前已验证用户的用户名,这将为我提供一个格式为DOMAIN \ USERNAME的用户名。 这很好用。

有没有一种简单的方法将其转换为显示名称(例如“Richard Gadsden”),就像XP开始菜单顶部显示的那样?

如果必须要这样做,我想我可以通过System.DirectoryServices并查询ADSI来完成,但肯定有更简单的方法吧?

3个回答

15

现在有一种更简单的方法,使用System.DirectoryServices.AccountManagement

Imports System.DirectoryServices.AccountManagement

...

   Dim CurrentUser As UserPrincipal = UserPrincipal.Current
   Dim DisplayName As String = CurrentUser.DisplayName 

2
只有在您可以从WindowsIdentity对象中获取UserPrincipal时,才能使用此功能。该问题依赖于对WindowsIdentity对象进行操作 - 并从中提取用户名。我可以看到如何从WindowsIdentity对象获取WindowsPrincipal,但找不到如何获取UserPrincipal的方法。 - Veverke
我在这里找到了答案(https://dev59.com/oU3Sa4cB1Zd3GeqPxbat#2809817),你可以根据域名简单地获取UserPrincipal。所以你的回答确实有帮助(但我的负评已经锁定了...请编辑你的回答,做出任何微小的改变,这样我就可以删除我的负评(SO的政策...)。 - Veverke
这个答案存在以下问题:
  • 它假设你正在尝试使用当前已验证的用户来完成操作,这在提问者的情况下似乎是正确的,但并不一定总是正确的。
  • 对于某些用户,UserPrincipal.Current无法正常工作(https://stackoverflow.com/questions/25491333/userprincipal-current-throws-invalidcastexception)- 这就是我试图通过从WindowsIdentity获取它来解决的问题。
- Stewart

2

6
你提供的链接文章有3页长度,我不确定该使用哪个代码。你能否在回答中专门发布所需的代码? - Brian McCarthy

1

我想ADSI是最好的选择。它非常简单。我没有看到更简单的方法。你只需要查询LDAP://<SID=user-sid>并获取区分名称属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接