为用户添加角色
Adding role to a user
我有这些代码,在使用管理员帐户添加新帐户时有效:
[Authorize(Roles = "Owner")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserProfile userprofile)
{
if (ModelState.IsValid)
{
db.UserProfiles.Add(userprofile);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userprofile);
}
但是当我添加这行代码时
Roles.AddUserToRole(userprofile.UserId.ToString(), "4");
我收到以下错误:
No user found was found that has the name "11".
我该怎么办?提前致谢!
您应该使用 UserName
而不是 UserId
、check MSDN 在此方法上:
public static void AddUserToRole(
string username,
string roleName
)
通知username
?也可能是您应该使用 roleName
而不是 RoleId
.
找到了答案,而且非常简单。首先,您需要调用您的数据库并添加以下代码:
webpages_UsersInRoles s = new webpages_UsersInRoles();
var userid = WebSecurity.GetUserId(model.UserName);
s.RoleId = roles;
s.UserId = userid;
db2.webpages_UsersInRoles.Add(s);
db2.SaveChanges();
这些是我在上述问题中缺少的代码。感谢帮助过的人!
我有这些代码,在使用管理员帐户添加新帐户时有效:
[Authorize(Roles = "Owner")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserProfile userprofile)
{
if (ModelState.IsValid)
{
db.UserProfiles.Add(userprofile);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userprofile);
}
但是当我添加这行代码时
Roles.AddUserToRole(userprofile.UserId.ToString(), "4");
我收到以下错误:
No user found was found that has the name "11".
我该怎么办?提前致谢!
您应该使用 UserName
而不是 UserId
、check MSDN 在此方法上:
public static void AddUserToRole(
string username,
string roleName
)
通知username
?也可能是您应该使用 roleName
而不是 RoleId
.
找到了答案,而且非常简单。首先,您需要调用您的数据库并添加以下代码:
webpages_UsersInRoles s = new webpages_UsersInRoles();
var userid = WebSecurity.GetUserId(model.UserName);
s.RoleId = roles;
s.UserId = userid;
db2.webpages_UsersInRoles.Add(s);
db2.SaveChanges();
这些是我在上述问题中缺少的代码。感谢帮助过的人!