无法在 dotnet Core 2.1 中创建新角色
Can't Create New Role In dotnet Core 2.1
我一直在阅读 dotnet 核心身份验证文档并尝试做一些示例。我能够创建新用户,但我 运行 遇到了创建新角色的问题。当我调用 RoleManager.CreateAsync 时,它不会创建新角色。
ApplicationContext Class:
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" });
}
当我调用 CreateRole 方法时,上下文已被释放。我将 create 方法添加到接口并从控制器调用它。它现在按预期工作。
我一直在阅读 dotnet 核心身份验证文档并尝试做一些示例。我能够创建新用户,但我 运行 遇到了创建新角色的问题。当我调用 RoleManager.CreateAsync 时,它不会创建新角色。
ApplicationContext Class:
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" });
}
当我调用 CreateRole 方法时,上下文已被释放。我将 create 方法添加到接口并从控制器调用它。它现在按预期工作。