我写了这段代码:
using(var _db = new ApplicationDbContext())
{
string roleName = "Admin";
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if(!roleManager.RoleExists(roleName))
{
var newRoleresult = roleManager.Create(new IdentityRole()
{
Name = roleName,
});
var userRole = new IdentityUserRole
{
UserId = System.Web.HttpContext.Current.User.Identity.GetUserId(),
RoleId = roleManager.FindByName(roleName).Id,
};
我只需要将userRole保存到表AspNetUserRoles。我怎么做?
答案 0 :(得分:1)
要将User
与Role
相关联,您需要使用AddToRole
方法UserManager
API:
public async Task<ActionResult> UserRole()
{
string roleName = "Admin";
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
if (!roleManager.RoleExists(roleName))
{
var newRoleresult = await roleManager.CreateAsync(new IdentityRole()
{
Name = roleName,
});
var result = await UserManager.AddToRoleAsync(
System.Web.HttpContext.Current.User.Identity.GetUserId(),
roleManager.FindByName(roleName).Name);
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First().ToString());
}
}
return View(); // If you have
}