3

我已经实施了 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 显示每个注册用户的角色,就像电子邮件、员工 ID 和电话号码一样。

控制器

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

任何意见,将不胜感激。

4

1 回答 1

0

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

var roles = await UserManager.GetRoles.Async();
var allUserRoles = String.Join(", ", roles);
_PTSUsersViewModel._roles = allUserRoles;
于 2014-09-03T22:22:49.777 回答