好吧我很浪费太多时间试图完成这个目标而且我有点沮丧,我想做的就是这样:
**表aspNetUserRoles 用户身份 角色ID
表aspNetRole
角色ID
RoleName **
我已经完成了第一部分,我已经使用种子方法填充了aspNetUserRoles,并在我的数据库中有一些角色,我已经创建了一个包含我所有角色的下拉列表,但是当我按下Register时遇到问题我得到一个错误:"未找到UserId"我将在这里展示我做了什么,并将放置我的2张桌子
我做了什么
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Sobre = model.Sobre, Idade = model.Idade, Telemóvel = model.Telemóvel, Nome = model.Nome };
var result = await UserManager.CreateAsync(user, model.Password);
var roleStore = new RoleStore<IdentityRole>(db);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(db);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(user.Id, "Name");
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
如果有人能让我解释我做错了什么我非常感激:)
答案 0 :(得分:0)
使用像这样
if (result.Succeeded)
{
userManager.AddToRole(user.Id, "Name");
}