我想将新注册的用户添加到我的应用程序中的通用"用户"角色.我正在使用ASP.NET身份.我的代码返回一个神秘的错误 - 异常详细信息:System.Configuration.Provider.ProviderException:找不到角色''.
我是否需要在帐户控制器(角色管理器等)中实例化某些内容?这里我的代码在AccountController中注册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);
}
Run Code Online (Sandbox Code Playgroud)
Lin*_*Lin 49
您需要使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
ASP*_*450 19
如果您正在使用内置身份验证管理器和帐户控制器,那么这样做:
UserManager.AddToRole(user.Id, "<Role>");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35885 次 |
| 最近记录: |