MVC Identity 2.0和管理角色

时间:2014-09-03 16:43:06

标签: 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>

视图模型

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; }
}

我的目标是使用grid.Column显示每个注册用户的角色,就像电子邮件,employeeID和phoneNumber一样。

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寻求一些提示或更好的方法时。

现在,请注意。在项目中已经创建了一些服务方法,这些方法在其他控制器方法中运行良好。也许这些可以在上面的问题中使用或修改:

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);
                }
            }
        }
    }

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用await UserManager.GetRolesAsync(user)返回分配了角色的字符串列表。由于用户可以拥有多个角色,因此没有&#34;用户角色&#34;,有角色。 因此,如果您想在表格中显示角色,则需要将其加入CSV格式。像这样:

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