c# - MVC Identity 2.0 和管理角色

标签 c# asp.net-mvc-5 asp.net-identity-2 mvcgrid

我已经实现了 Identity 2.0 成员资格,现在开始后悔了。但是,我在这个项目中如此深入,没有回头路可走。我的问题对大多数人来说可能很简单,所以希望我能得到一些帮助。

我的 MVC5 应用程序中有一个网格控件。

查看

@using System.Web.Helpers;
@model List<PTSPortal.Models.PTSUsersViewModel>
@{
    var grid = new WebGrid(source: Model, defaultSort: "PropertyName", rowsPerPage: 10);
 }
 <div id="ContainerBox">
    @grid.GetHtml(columns: grid.Columns(
            grid.Column("_email", "Email", canSort: true, style: "text-align-center"),
            grid.Column("_employeeID", "EmployeeID", canSort: true, style: "text-align-center"),
            grid.Column("_phoneNumber", "Phone", canSort: true, style: "text-align-center")
            //-----I want to display the user's role here!------
        ))
</div>

View 模型

public class PTSUsersViewModel
{
    public string _ID { get; set; }
    public string _email { get; set; }
    public int? _employeeID { get; set; }
    public string _phoneNumber { get; set; }
    public string _role { get; set; }
}

我的目标是使用网格显示每个注册用户的角色。列就像电子邮件、员工 ID 和电话号码一样。

Controller

public ActionResult PTSUsers()
{
        List<PTSUsersViewModel> viewModel = FetchInfo().ToList();
        return View(viewModel);
}

private static IEnumerable<PTSUsersViewModel> FetchInfo()
{

        PTSPortalEntities context = new PTSPortalEntities();

        using (ApplicationDbContext _context = new ApplicationDbContext())
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));

        }

        return (from a in context.AspNetUsers
                orderby a.Email ascending
                select new PTSUsersViewModel
                {
                    _ID = a.Id,
                    _email = a.Email,
                    _employeeID = a.EmployeeID,
                    _phoneNumber = a.PhoneNumber,
                    //_role = ........
                }).ToList<PTSUsersViewModel>();
}

在我的 using 语句中,我有 var roleManager 和 var userManager,但它们什么也没做。我试图检索用户的角色,但就在那时我停下来并想我会联系 SOF 寻求一些提示或更好的方法。

现在,旁注。项目中已经创建了一些服务方法,它们在其他 Controller 方法中工作得很好。也许这些可以在我上面的问题中使用或修改:

public class AppServices
{
    // Roles used by this application
    public const string AdminRole = "Admin";
    public const string TrainerRole = "Trainer";

    private static void AddRoles(ref bool DataWasAdded)
    {
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

        if (roleManager.RoleExists(AdminRole) == false)
        {
            Guid guid = Guid.NewGuid();
            roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = AdminRole });
            DataWasAdded = true;
        }
        if (roleManager.RoleExists(TrainerRole) == false)
        {
            Guid guid = Guid.NewGuid();
            roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = TrainerRole });
            DataWasAdded = true;
        }
    }

    /// <summary>
    ///  Checks if a current user is in a specific role.
    /// </summary>
    /// <param name="role"></param>
    /// <returns></returns>
    public static bool IsCurrentUserInRole(string role)
    {
        if (role != null)
        {
            using (ApplicationDbContext _context = new ApplicationDbContext())
            {
                var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
                if (UserManager.IsInRole(GetCurrentUserID(), role))
                {
                    return true;
                }
            }
        }
        return false;
    }

    /// <summary>
    /// Adds a user to a role
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="RoleToPlaceThemIn"></param>
    public static void AddUserToRole(string userId, string RoleToPlaceThemIn)
    {
        // Does it need to be added to the role?
        if (RoleToPlaceThemIn != null)
        {
            using (ApplicationDbContext _context = new ApplicationDbContext())
            {
                var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
                if (UserManager.IsInRole(userId, RoleToPlaceThemIn) == false)
                {
                    UserManager.AddToRole(userId, RoleToPlaceThemIn);
                }
            }
        }
    }

如有任何建议,我们将不胜感激。

最佳答案

使用 await UserManager.GetRolesAsync(user) 返回已分配角色的字符串列表。因为用户可以有很多角色,所以没有“用户角色”这样的东西,只有角色。 因此,如果您想在表中显示角色,则需要将它们加入 CSV 文件中。像这样:

var roles = await UserManager.GetRoles.Async();
var allUserRoles = String.Join(", ", roles);
_PTSUsersViewModel._roles = allUserRoles;

关于c# - MVC Identity 2.0 和管理角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649591/

相关文章:

c# - Entity Framework - 无法创建类型的常量值

asp.net - MVC 5 & Angular 2 Multiple "Siloed"应用程序结构建议

c# - ASP.NET Identity 2.0 随机无效 token

C# MVC5 View 无法识别命名空间

asp.net - typescript 在构建时编译不起作用

asp.net-identity - ASP.NET 标识 : Why User Properties AND Claims?

asp.net - Identity 2.0 Code First 表重命名

C# Winforms 大小调整和控制

c# - 如何禁用新行的特定 DataGrid 单元格

c# - Designer.Cs 文件未注册命名空间更新