如何在MVC5中为用户分配角色? [英] How to assign a Role to a user in MVC5?

查看:85
本文介绍了如何在MVC5中为用户分配角色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC4中,我正在使用代码

In MVC4 I was using the code

Roles.AddUserToRole(User.Identity.Name, "Approved");

在MVC5身份模型中,是否还有其他方法可以做到这一点(将用户添加到已批准"角色中)?

Is there any other way of doing the same(adding user to role "Approved") in MVC5 Identity Model?

编辑:我的意思是问这是将用户添加到角色的正确方法吗?因为在许多示例中,他们不使用此代码.

I meant to ask is this the right way of adding a user to a role? Because in a lot of examples they do not use this code.

推荐答案

您可以在任何类型为UserManager<TUser>的对象上调用AddToRoleAddToRoleAsync作为实例方法,以在MVC 5中实现它,如下所示:

You can call AddToRole or AddToRoleAsync as an instance method on any object of type UserManager<TUser> to achieve it in MVC 5, like below:

var _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
UserManager.AddToRole("UserName", "UserRole");

有关更多详细信息,请查看以下链接:

For more details, take a look at the following link:

http://msdn.microsoft.com/en-us/library/dn468199(v=vs.111).aspx

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆