如何在ASP.NET Core中获取Active Directory当前用户的显示名称?

4

我正在使用 C# ASP.NET Core (MVC 6) 连接到本地的 Active Directory。我可以通过以下方式简单地获取当前用户的 用户名

public MyModel(IHttpContextAccessor httpContextAccessor)
{
    string userName = httpContextAccessor.HttpContext.User.Identity.Name;
}

我得到了"DOMAIN\jsmith",但我需要获取显示名称,即"John Smith"。我该怎么做?

更新:经过更多的挖掘,目前似乎还没有这个功能:https://github.com/dotnet/corefx/issues/2089


您可以与身份提供者(如ADFS或Identity Server)进行WS-Federation,该提供者可以返回包括显示名称在内的声明。 - Wiktor Zychla
3个回答

4
Novell的ldap库已经移植到.NET Core。由于显示名称是一个属性,因此您应该能够使用该库查询它(尽管没有特定的示例)。

-1
您需要创建到Active Directory的连接,通过sAMAccountName属性查找用户并查询其displayName属性。
var domain = httpContextAccessor.HttpContext.User.Identity.Name.Split('\\').First();
var accountName = httpContextAccessor.HttpContext.User.Identity.Name.Split('\\').Last();

using (var entry = new DirectoryEntry($"LDAP://{domain}"))
{
    using (var searcher = new DirectorySearcher(entry))
    {
        searcher.Filter = $"(sAMAccountName={name})";
        searcher.PropertiesToLoad.Add("displayName");
        var searchResult = searcher.FindOne();

        if (searchResult != null && searchResult.Properties.Contains("displayName"))
        {
            var displayName = searchResult.Properties["displayName"][0];
        }
        else
        {
            // user not found
        }
    }
}

这个程序是兼容 ASP.NET Core (MVC 6) 的吗?除非我使用了错误的包,否则 DirectoryEntryusing 中不起作用,因为它没有实现 IDisposible,我甚至找不到一个与 ASP.NET Core 兼容的 DirectorySearcher 的参考。 - Serj Sagan
抱歉,完全错过了。以为你只需在项目中包含System.DirectoryServices dll。但事实并非如此。请查看https://dev59.com/xZXfa4cB1Zd3GeqPaiWx。如果这没有帮助,一种极端的方法是将代码移动到单独的进程中,然后启动进程并通过文件\进程默认输出重定向\IPC等方式获取结果。(这种方法在ASP.NET Core中得到支持) - oldovets
这些命名空间在Core中不存在。但是,还没有。 - blowdart
@oldovets(或其他任何人)不幸的是,在Core 1.1中,它们又回到了.csproj文件,并且显然您不能再简单地引用GAC库。 - Scott Fraley
如果您安装了System.DirectoryServices Nuget包,这将起作用。 - Mr. TA

-2

我曾经遇到过同样的问题。经过一番研究和浏览微软文档,我找到了解决方案。

首先使用Nuget包管理器安装System.DirectoryServices.AccountManagement包。

然后在调用GetUserNameWithoutDomain方法时,将以下内容作为参数传递:

GetUserNameWithoutDomain(UserPrincipal.Current.GivenName, UserPrincipal.Current.Surname);


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