我想将新注册的用户添加到我的应用程序中的通用“用户”角色。我正在使用 ASP.NET 标识。我下面的代码返回一个神秘的错误 - 异常详细信息:System.Configuration.Provider.ProviderException:找不到角色“”。
我是否需要在我的帐户 Controller (角色管理器等)中实例化某些内容?
这是我在 AccountController Register POST 操作中的代码。
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
var person = new Person() {
UserName = user.UserName,
UserId = user.Id,
LastName = model.LastName,
FirstName = model.FirstName,
Email = model.Email,
PhoneCell = model.PhoneCell };
Roles.AddUserToRole(model.UserName, "User");
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
db.People.Add(person);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
最佳答案
您需要使用 UserManager
为用户添加角色。见下文:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
using (var context = new ApplicationDbContext())
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(user.Id, "User");
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
}
关于asp.net-mvc - 在 MVC 5 中注册后为用户添加角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20841262/