我一直在阅读dotnet核心身份验证文档,并尝试做一些示例。我可以创建新用户,但是在创建新角色时遇到了问题。当我调用RoleManager.CreateAsync时,它不会创建新角色。
ApplicationContext类:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<string>, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
startup.cs:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration["AppSetting:DefaultConnection"]));
services.AddIdentity<ApplicationUser, IdentityRole<string>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
我的存储库:
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signManager;
private readonly ApplicationDbContext _context;
private readonly RoleManager<IdentityRole<string>> _roleManager;
public AccountRespository(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signManager, ApplicationDbContext context, RoleManager<IdentityRole<string>> roleManager)
{
_signManager = signManager;
_userManager = userManager;
_context = context;
_roleManager = roleManager;
}
我在转发中创建角色方法
public async Task CreateRoles(string roleName)
{
await _roleManager.CreateAsync(new IdentityRole() { Name = "Admin" });
}
答案 0 :(得分:0)
当我调用CreateRole方法时,上下文已被释放。我将create方法添加到接口并从控制器调用它。现在它正在按预期工作。