簡體   English   中英

MVC Identity 2.0和管理角色

[英]MVC Identity 2.0 and managing roles

我已經實現了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顯示每個注冊用戶的角色,就像email,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);
                }
            }
        }
    }

任何意見,將不勝感激。

使用await UserManager.GetRolesAsync(user)返回分配了角色的字符串列表。 因為用戶可以有很多角色,所以沒有“用戶角色”這樣的東西,有角色 因此,如果您想在表格中顯示角色,則需要將它們加入CSV。 像這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM