我创建了自己的数据库,并通过更改连接字符串向其中添加用户标识表。现在我的连接字符串是这样的:
当我创建一个新用户时,它运行良好。但是当我更改RegisterControler中的Register(RegisterViewModel模型)以将用户添加到角色时,如下代码所示:公共异步任务寄存器(RegisterViewModel模型){if(ModelState.IsValid){var user=new ApplicationUser(){UserName=model.Email,Email=model.Email};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//add user to member role******************
if (!Roles.RoleExists("Member"))
Roles.CreateRole("Member");
Roles.AddUserToRole(model.Email, "Member");
//*******************************************
await SignInAsync(user, isPersistent: 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");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
用户注册但不添加到成员角色!似乎还有另一个角色的连接字符串!beacause当我们运行在App_Data中创建的ASPNETDB.MDF代码时!
请帮我解决这个问题
为了在asp.net标识中创建角色,您需要使用与当前使用AspNetUserManager相同的AspNetRoleManager。
AspNetUserManager可能如下所示。
public class AspNetRoleManager : RoleManager<IdentityRole, string>
{
public AspNetRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static AspNetRoleManager Create(IdentityFactoryOptions<AspNetRoleManager> options, IOwinContext context)
{
return new AspNetRoleManager(new RoleStore<IdentityRole, string, IdentityUserRole>(context.Get<YourDataContext>()));
}
}
然后,您需要在owin启动中注册AspNetRoleManager。与AspNetUserManager相同。
app.CreatePerOwinContext<AspNetRoleManager>(AspNetRoleManager.Create);
之后,您可以在控制器中使用它来创建角色。
var roleManager=HttpContext.GetOwinContext().Get();
//检查现有角色
var roleManager = HttpContext.GetOwinContext().Get<AspNetRoleManager>();
var roleExists = await roleManager.RoleExistsAsync("Member");
if (!roleExists)
{
var role = new IdentityRole();
role.Name = "Member";
var result = roleManager.CreateAsync(role);
}
然后向用户添加新角色。
var user = await UserManager.FindByEmailAsync(model.Email);
var roleRsult = UserManager.AddToRole(user.Id, roleName);