C# 在 .NET Web 应用程序中获取登录用户的 UPN 或电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1101938/
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-06 08:16:34  来源:igfitidea点击:

Get UPN or email for logged in user in a .NET web application

c#.netactive-directory

提问by DrStalker

I'm not a .NET developer, and I have a feeling this would be trivial for someone who is:

我不是 .NET 开发人员,我觉得这对于以下人员来说是微不足道的:

I have a C# web application that makes user of the user credentials of the logged in user. Currently it uses the SID which comes from

我有一个 C# web 应用程序,它使用户使用登录用户的用户凭据。目前它使用来自的 SID

System.Security.Principal.WindowsIdentity.GetCurrent().User.Value 

I need to get either the users UPN login or email address (as defined in active directory) instead of the SID. GetCurrent() returns an object of type WindowsIdentity; looking in the details for WindowsIdentity Members:

我需要获取用户 UPN 登录名或电子邮件地址(在活动目录中定义)而不是 SID。GetCurrent() 返回 WindowsIdentity 类型的对象;查看 WindowsIdentity 成员的详细信息:

MSDN: WindowsIdentity Members

MSDN:WindowsIdentity 成员

I can't see anything that looks like it would give me either the UPN or email in there. How can I pull up that information to use, either by feeding the SID into some other function or calling something different in the first place.

我看不到任何看起来会给我 UPN 或电子邮件的内容。我如何提取要使用的信息,或者通过将 SID 提供给其他函数或首先调用不同的东西。

采纳答案by Kiki

Meanwhile (.NET 3.5) this is a one-liner:

同时(.NET 3.5)这是一个单行:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.EmailAddress

for the email, or

对于电子邮件,或

System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName

for the UPN.

对于 UPN。

回答by Jimmy Chandra

Try:

尝试:

System.Security.Principal.WindowsIdentity.GetCurrent().Name

回答by Alex Peck

To query active directory using a directory searcher you need to do something like this (totally untested code):

要使用目录搜索器查询活动目录,您需要执行以下操作(完全未经测试的代码):

    string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    string ldapPath = "LDAP://domain.company.com";

    public string GetEmail(string userName, string ldapPath)
    {
        using (DirectoryEntry root = new DirectoryEntry(ldapPath))
        {
            DirectorySearcher searcher = new DirectorySearcher(root);
            searcher.Filter = string.Format(@"(&(sAMAccountName={0}))", userName);
            searcher.PropertiesToLoad = "mail";

            SearchResult result = searcher.FindOne();

            if (result != null)
            {
                PropertyValueCollection property = result.Properties["mail"];
                return (string)property.Value;
            }
            else
            { 
                // something bad happened
            }
        }
    }