Asp.net mvc 5 ASP.NETMVC5:使用标识如何在登录后将角色附加到用户

Asp.net mvc 5 ASP.NETMVC5:使用标识如何在登录后将角色附加到用户,asp.net-mvc-5,asp.net-identity,Asp.net Mvc 5,Asp.net Identity,我们通过这种方式保护具有特定角色名称的authorize属性的操作 [Authorize(Roles="members, admin")] 假设用户和角色映射到db表中。所以,当用户登录时,我如何将角色附加到使用标识登录的用户 在这里,我发布了url和示例,展示了人们如何在mvc4中使用自定义表单身份验证执行相同的操作。只要看一下代码,我就一定能理解我使用identity对asp.net mvc 5所做的事情。 请参阅上面的url,了解asp.net mvc 4的自定义表单身份验证 prote

我们通过这种方式保护具有特定角色名称的authorize属性的操作

[Authorize(Roles="members, admin")]
假设用户和角色映射到db表中。所以,当用户登录时,我如何将角色附加到使用标识登录的用户

在这里,我发布了url和示例,展示了人们如何在mvc4中使用自定义表单身份验证执行相同的操作。只要看一下代码,我就一定能理解我使用identity对asp.net mvc 5所做的事情。 请参阅上面的url,了解asp.net mvc 4的自定义表单身份验证

protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now                
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;

                //let us extract the roles from our own custom cookie
                string roles = DBHelper.GetUserRoles(username);

                //Let us set the Pricipal with our user specific details
                e.User = new System.Security.Principal.GenericPrincipal(
                  new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
            }
            catch (Exception)
            {
                //somehting went wrong
            }
        }
    }
}

我正在使用asp.NETMVC5&identity系统。请帮助和引导我。谢谢

您必须先登录用户id

var UserName= await User.Identity.GetUserId()
然后,您可以将任何角色分配给登录的用户,如

var _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
UserManager.AddToRole("UserName", "UserRole");
var\u context=new ApplicationDbContext();
var UserManager=newusermanager(newuserstore(_context));
AddToRole(“用户名”、“用户角色”);

我猜AddToRole会将角色添加到db表中。这一行如何将角色添加到登录用户的通用主体中?请参阅这一行代码
e.user=new System.Security.principal.GenericPrincipal(new System.Security.principal.GenericEntity(username,“Forms”)、roles.Split(“;”)如何使用标识完成此操作?此链接将帮助您实现您正在尝试的功能,我只想知道,在mvc5中,当用户登录时,是否会自动获取用户特定的角色并将其分配给GenericPrincipal()?如果lazyload为false,那么mvc在登录后将如何从userrole和role表加载数据……如何处理这种情况?您得到答案了吗?