MVC 5获取当前用户RoleNames

时间:2016-12-05 11:34:06

标签: asp.net asp.net-mvc-5

这里我需要列出当前的用户角色,例如,如果我有很多角色,如管理员,操作员,编辑器,编写器等,并且一个用户名(userone)处于两个角色,我将如何能够列出角色喜欢:

class Vote < ActiveRecord::Base
  belongs_to :user
  belongs_to :vote_option
end

def surv_params
  params.require(:surv).permit(:topic, :votingtype,
    polls_attributes: [:id, :topic, :endtime, :endontime, :_destroy,
    vote_options_attributes: [:id, :title, :_destroy]
    ])
end

为此我发现了这段代码,但是有任何简单或更好的方法:

user name : userone 
roles     : editor,writer

肯定在视图中你需要调用ViewBag.selectedRoleName

所以这里如果看到上一个角色名称中有(,)额外的内容,那么只需要提前更好地搜索

1 个答案:

答案 0 :(得分:0)

以下是视图:

javadoc

以下是观点:

    public class UsersAdminController : Controller
{
    public UsersAdminController()
    {
    }

    public UsersAdminController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }

    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    private ApplicationRoleManager _roleManager;
    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

    public async Task<ActionResult> Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var user = await UserManager.FindByIdAsync(id);

        ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);

        return View(user);
    } 
  }