创建管理员用户时出现问题



我在控制器中使用创建管理员用户时遇到问题。这里有什么问题?

这是我的代码:

public class ProductsController : Controller
{
    private SwagExchangeDb db = new SwagExchangeDb();
    protected override void Initialize(RequestContext requestContext)
    {
        var ac  = new ApplicationDbContext();
        var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(ac));
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ac));
        var user = new ApplicationUser { UserName = "hello@gmail.com", Email = "hello@gmail.com"};
        userManager.Create(user, "Hello1234!");
        roleManager.Create(new IdentityRole("admin"));
        userManager.AddToRole(user.Id, "admin");
    }

收到错误:

System.InvalidOperationException:"找不到 UserId。

您正在尝试通过您没有的 ID 查找用户。创建用户后,需要查询用户。此外,您应该在使用完上下文后对其进行处置:

protected override void Initialize(RequestContext requestContext)
{
    using (var ac  = new ApplicationDbContext())
    {
        var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(ac));
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ac));
        var user = new ApplicationUser { UserName = "hello@gmail.com", Email = "hello@gmail.com"};
        userManager.Create(user, "Hello1234!");
        roleManager.Create(new IdentityRole("admin"));
        user = userManager.FindByNameAsync(user.UserName).Result;
        userManager.AddToRole(user.Id, "admin");
    }
}

相关内容

  • 没有找到相关文章

最新更新