C# User.Identity.Name 中的全名而不是域 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/494006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:34:41  来源:igfitidea点击:

Full name rather than the domain id in User.Identity.Name

c#authenticationidentityadsi

提问by

The User.Identity.Nameproperty returns the domain login id.

User.Identity.Name属性返回域登录 ID。

Which class/property exposes the actual user name?

哪个类/属性公开了实际的用户名?

For user "John Doe" who logs into the web application supplying my_domain\jdoe

对于登录到提供 my_domain\jdoe 的 Web 应用程序的用户“John Doe”

**User.Identity.Name -** 
Returns : *my_domain\jdoe*

**System.Environment.UserName**
Returns: *jdoe*

Which class/property returns? ... "John Doe"

哪个类/属性返回?......“约翰·多伊”

回答by Ken Browning

The IIdentity interface is that which provides the Name property on User.Identity. The IIdentity interface can be implemented on any number of classes which know how to lookup users from a data-store (SQL Server, Active Directory, etc).

IIdentity 接口是在 User.Identity 上提供 Name 属性的接口。IIdentity 接口可以在知道如何从数据存储(SQL Server、Active Directory 等)中查找用户的任意数量的类上实现。

There is no property of the IIdentity interface which provides "John Doe". If that information is located in your data-store then you'll need to use the tools specific to that data-store to access it.

IIdentity 接口没有提供“John Doe”的属性。如果该信息位于您的数据存储中,那么您将需要使用特定于该数据存储的工具来访问它。

That said, its entirely possible that the object which is returned by User.Identity has a property which contains "John Doe" that you might be able to access through some other interface besides IIdentity (our custom IIdentity implementation does this, for example).

也就是说,由 User.Identity 返回的对象完全有可能具有包含“John Doe”的属性,您可以通过除 IIdentity 之外的其他接口访问该属性(例如,我们的自定义 IIdentity 实现就是这样做的)。

回答by barneytron

Sounds like instead of the login name, you are after the display name of an Active Directory user account. What you might want to do is to do an AD search (DirectorySearcher) and get the display name from the search result property.

听起来您不是登录名,而是 Active Directory 用户帐户的显示名称。您可能想要做的是进行 AD 搜索 (DirectorySearcher) 并从搜索结果属性中获取显示名称。

I'm assuming that you are in an AD environment, since you tagged the question adsi.

我假设您处于 AD 环境中,因为您标记了问题 adsi。

Note:If you are working with .NET 3.5, you might want to look at tvanfosson's post.

注意:如果您使用 .NET 3.5,您可能需要查看 tvanfosson 的帖子。

回答by tvanfosson

If you are thinking Active Directory, you'll need to find the UserPrincipal that corresponds to the given samAccountName and get the DisplayName property from it. Note that it may not be set.

如果您考虑使用 Active Directory,则需要找到与给定 samAccountName 对应的 UserPrincipal 并从中获取 DisplayName 属性。请注意,它可能未设置。

string fullName = null;
using (PrincipalContext context = new PrincipalContext( ContextType.Domain ))
{
    using (UserPrincipal user
            = UserPrincipal.FindByIdentity( context,
                                            User.Identity.Name ))
    {
        if (user != null)
        {
            fullName = user.DisplayName;
        }
    }
}

回答by Oscar Cabrero

using System.DirectoryServices;


public static string GetFullName(string strLogin)
    {
        string str = "";
        string strDomain;
        string strName;

        // Parse the string to check if domain name is present.
        int idx = strLogin.IndexOf('\');
        if (idx == -1)
        {
            idx = strLogin.IndexOf('@');
        }

        if (idx != -1)
        {
            strDomain = strLogin.Substring(0, idx);
            strName = strLogin.Substring(idx + 1);
        }
        else
        {
            strDomain = Environment.MachineName;
            strName = strLogin;
        }

        DirectoryEntry obDirEntry = null;
        try
        {
            obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
            System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
            object obVal = coll["FullName"].Value;
            str = obVal.ToString();
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }
        return str;
    }

and the you can just call

你可以打电话

var strJonDoeName = GetFullName(User.Identity.Name)

code mock it from here

代码从这里模拟它

回答by HerrB

Maybe I have made a mistake somewhere, but WinNT://... hasn't worked for domain accounts for me. Additionally, if the user isn't in the same domain as the machine, than PrincipalContext may not find the wanted element (as it searches in the current context, if used as above).

也许我在某个地方犯了一个错误,但是 WinNT://... 对我来说对域帐户不起作用。此外,如果用户与机器不在同一个域中,那么 PrincipalContext 可能找不到想要的元素(因为它在当前上下文中搜索,如果如上所述使用)。

The following should translate the "friendly domain name" as provided by User.Identity.Name to an ldap compliant domain. Using the distinguishName of the domain delivers the needed ldap path information (which has solved my cross domain problem):

以下内容应将 User.Identity.Name 提供的“友好域名”转换为符合 ldap 的域。使用域的 distinctName 传递所需的 ldap 路径信息(解决了我的跨域问题):

(VB.NET, sorry)
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
...

Dim strUserName As String
Dim objDirContext As DirectoryContext
Dim objContext As PrincipalContext
Dim objPrincipal As Principal
Dim strLDAPDomainPath As String
...

// User.Identity.Name delivers domain\account or account@domain
// Split User.Identity.Name in domain and account as specified above
strDomain = "my_domain"
strAccount = "jdoe"

// Get LDAP domain relative path (distinguishName) from short domain name (e.g. my_domain -> us.my_domain.com -> DC=us,DC=my_domain,DC=com)
Try
    objDirContext = New DirectoryContext(DirectoryContextType.Domain, strDomain)
    strLDAPDomainPath = Domain.GetDomain(objDirContext).GetDirectoryEntry.Properties("distinguishedName").Value.ToString
Catch objException As DirectoryServicesCOMException
    Throw New Exception("Couldn't get LDAP domain: " & objException.Message)
End Try

// Find user in LDAP
// Nothing results in using current domain controller
Try
   objContext = New PrincipalContext(ContextType.Domain, Nothing, strLDAPDomainPath)
   objPrincipal = Principal.FindByIdentity(objContext, IdentityType.Name, strAccount)

   If Not IsNothing(objPrincipal) Then
      strUserName = objPrincipal.DisplayName
   End If
Catch objException As Exception
   Throw New Exception("Couldn't get user display name: " & objException.Message)
End Try

// strUserName should now contain the wanted full name