[英]adding roles in asp.net mvc 4 application using identity provider
I have a ASP.NET MVC 4 Web Application "APP1" which has Entity Framework implemented using the DB First approach. 我有一个ASP.NET MVC 4 Web应用程序“ APP1”,该应用程序具有使用DB First方法实现的实体框架。 I'm using the automatically generated Account
- model
, - views
and - controller
for Authentication. 我正在使用自动生成的Account
model
,- views
和- controller
进行身份验证。
So far, everything seems fine. 到目前为止,一切似乎还不错。 I can add new users and log in. My question now is: How can I add roles to my users? 我可以添加新用户并登录。我现在的问题是: 如何向用户添加角色? I basically only need 1 role. 我基本上只需要1个角色。
Additional Information 附加信息
I made 2 small modifications: 我做了2个小修改:
The following tables were automatically generated at my EF SQL Server DB 下表是在我的EF SQL Server数据库中自动生成的
UPDATE 更新
I ended up with creating them manually. 我最终手动创建了它们。 See my TSQL Code bellow 看下面的我的TSQL代码
INSERT INTO webpages_Roles (RoleName) VALUES ('canEdit')
INSERT INTO webpages_UsersInRoles (UserId, RoleId) VALUES (2, 1)
To make an ActionResult
available only for authorized persons with a specific role, I decorated them as follow: 为了使ActionResult
仅适用于具有特定角色的授权人员,我将它们装饰如下:
[Authorize(Roles = "canEdit")]
public ActionResult Index()
{
// return View();
}
For Identity v1, the code is: 对于Identity v1,代码为:
var username = "Fred";
var roleName = "Administrator";
Roles.AddUserToRole(username, roleName);
If you are using Identity v2 (assuming you have your userManager object): 如果使用的是Identity v2(假设您有userManager对象):
var username = "Fred";
var roleName = "Administrator";
var user = await userManager.FindByNameAsync(username);
userManager.AddToRole(user.Id, roleName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.