使用asp.net身份

时间:2015-09-14 21:54:16

标签: asp.net-mvc-5 asp.net-identity

我遇到登录问题,即使我看到表格中填充了来自Configuration.cs的种子用户信息:

protected override void Seed(www.Models.ApplicationDbContext context)
        {
            if (!context.Roles.Any(x => x.Name == "admin"))
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);
                var role = new IdentityRole { Name = "admin" };
                roleManager.Create(role);
            }

            if (!context.Users.Any(x => x.UserName == "admin" && x.Email == "admin@admin.com"))
            {
                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);
                var user = new ApplicationUser { UserName = "admin", Email = "admin@admin.com" };
                var hasher = new PasswordHasher();
                userManager.Create(user, "MySecret5");
                userManager.AddToRole(user.Id, "admin");
            }
        }

当我尝试登录时,我收到错误“无效登录尝试”。 我错过了什么?

编辑: 我正在学习所有关于asp.net的东西,所以我现在非常大的菜鸟:(所以我发现这个例子对我有用,如果有人需要它在这里它是:

protected override void Seed(www.Models.ApplicationDbContext context)
        {
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            if (!context.Users.Any(x => x.UserName == "admin@v.com"))
            {
                var user = new ApplicationUser { UserName = "admin@v.com", Email = "admin@v.com" };
                userManager.Create(user, "Password5%");
                context.Roles.AddOrUpdate(x => x.Name, new IdentityRole { Name = "admin" });
                context.SaveChanges();
                userManager.AddToRole(user.Id, "admin");
            }
        }

感谢您的所有帮助和时间。

2 个答案:

答案 0 :(得分:4)

使用种子用户登录的问题似乎与MVC不准确有关,请看:

var result = await SignInManager.PasswordSignInAsync(model.Emali, model.Password, model.RememberMe, shouldLockout: false);

如果我们为这个用户播种:

var user = new ApplicationUser { UserName = "SomeName", Email = "admin@v.com" };

结果将是== false ,但如果我们将 model.Emali 更改为 model.UserName ,则登录结束并成功 - 当然,现在当我们登录时,我们必须提供UserName例如:

UserName:SomeName;

Passwort:Password5%;

答案 1 :(得分:3)

这对我来说完美无缺。

protected override void Seed(www.Models.ApplicationDbContext context)
        {
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            if (!context.Users.Any(x => x.UserName == "admin@v.com"))
            {
                var user = new ApplicationUser { UserName = "admin@v.com", Email = "admin@v.com" };
                userManager.Create(user, "Password5%");
                context.Roles.AddOrUpdate(x => x.Name, new IdentityRole { Name = "admin" });
                context.SaveChanges();
                userManager.AddToRole(user.Id, "admin");
            }
        }