在注册时将用户添加到角色mvc 5 [英] Adding user to role upon registration mvc 5
本文介绍了在注册时将用户添加到角色mvc 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个角色Admin and Donor
注册后,任何用户都必须加入Donor角色。如何使用identity和mvc5实现此目的。
I have 2 roles Admin and Donor
Upon registration any user must be added to the Donor role. How do I achieve this with identity and mvc5.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = model.GetUser();
var result = await UserManager.CreateAsync(user, model.Password);
UserManager.AddToRole(user.UserName, "User");
if (result.Succeeded)
{
return RedirectToAction("Index", "Account");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
我收到以下错误System.InvalidOperationException:找不到UserId。
I getthe following error System.InvalidOperationException: UserId not found.
推荐答案
首先检查结果,然后只添加角色。这意味着更改UserManager.AddToRole的位置,如:
First check for result, then only add role. That mean change the position of UserManager.AddToRole like:
var user = model.GetUser();
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
result = UserManager.AddToRole(user.Id, "User");
如果您有角色列表,也可以添加多个角色。
You can add multiple roles too if you have a list of roles.
foreach(var role in roles)
{
var isInRole = await UserManager.IsInRoleAsync(userid, role)
if(!isInRole)
{
await UserManager.AddToRoleAsync(userid, role);
}
}
这篇关于在注册时将用户添加到角色mvc 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文