c# - 在字符串 [] 中返回用户所属的所有 Active Directory 组的列表

标签 c# asp.net-mvc-3 asp.net-mvc-4 c#-4.0 active-directory

我需要返回用户所属的所有 Active Directory 组,但在字符串 [ ] 中,因此我可以在通用主体中使用结果。

我不确定是否要投出结果?请帮忙!

string[] roles = new string[] {  
helper.GetActiveDirectoryGroups(User.Identity.Name) };

GenericPrincipal principal = new GenericPrincipal(identity,roles);

 public string[] GetActiveDirectoryGroups(string userName)
    {
          //code here

    }

最佳答案

这应该可以解决问题。

using System.DirectoryServices.AccountManagement;

public static string[] GetGroups(string username)
{
    string[] output = null;

    using (var ctx = new PrincipalContext(ContextType.Domain))
    using (var user = UserPrincipal.FindByIdentity(ctx, username))
    {
        if (user != null)
        {
            output = user.GetGroups() //this returns a collection of principal objects
                .Select(x => x.SamAccountName) // select the name.  you may change this to choose the display name or whatever you want
                .ToArray(); // convert to string array
        }
    }

    return output;
}

关于c# - 在字符串 [] 中返回用户所属的所有 Active Directory 组的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34319263/

相关文章:

c# - Xamarin.Forms 绑定(bind)指定的转换无效

asp.net-mvc-3 - 将 mvc-mini-profiler 与 EF 4.0 和 Ninject 结合使用

jquery - 从 MVC4 中的 @Html.ValidationSummary() 中删除项目符号

asp.net-mvc - MVC4 TextBoxFor 覆盖模型属性

asp.net - 在 Asp.net mvc4 应用程序中向 webgrid 添加垂直滚动

asp.net-mvc-4 - ASP.NET MVC 4 - 从 Controller 添加包?

使用 Windows API Code Pack Shell 扩展的 C# 应用程序不会关闭

c# - 使用 FileStream 在 C# 中打开文件

c# - CaSTLe Windsor 争论不休的生活方式

vb.net - 使用 VB.NET 的 MVC3 Razor View 项目在所有 vbhtml 页面的错误列表窗口中给出语法错误