Saya telah bermain-main dengan MVC 5, saya memiliki beberapa model, controller dan views setup menggunakan kode pertama migrasi.
Pertanyaan saya adalah bagaimana saya benih pengguna dan peran? Saya saat ini benih beberapa referensi data dalam metode Benih di Konfigurasi.cs. Tapi tampaknya bagi saya bahwa pengguna dan peran tabel tidak dibuat sampai sesuatu yang pertama adalah AccountController.
Saat ini saya memiliki dua koneksi string sehingga aku dapat memisahkan data saya dari saya otentikasi ke database yang berbeda.
Bagaimana saya bisa mendapatkan pengguna, peran, dll tabel mengisi bersama dengan orang lain? Dan bukan ketika akun pengendali memukul?
Berikut ini adalah contoh biasa Benih pendekatan:
protected override void Seed(SecurityModule.DataContexts.IdentityDb context)
{
if (!context.Roles.Any(r => r.Name == "AppAdmin"))
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = "AppAdmin" };
manager.Create(role);
}
if (!context.Users.Any(u => u.UserName == "founder"))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser {UserName = "founder"};
manager.Create(user, "ChangeItAsap!");
manager.AddToRole(user.Id, "AppAdmin");
}
}
Saya menggunakan paket-manager "update-database". DB dan semua tabel yang dibuat dan diunggulkan dengan data.
It's kecil itu, tapi untuk siapa pun yang memiliki "UserId tidak ditemukan." pesan ketika mencoba untuk benih: (Tom Regan punya pertanyaan ini di kolom komentar, dan saya terjebak sendiri untuk sementara)
Ini berarti bahwa manajer.Membuat(pengguna, "ChangeItAsap!") itu tidak berhasil. Ini mungkin memiliki alasan yang berbeda, tapi bagi saya itu adalah karena password saya tidak berhasil untuk validasi.
Aku punya kebiasaan passwordvalidator, yang tidak dipanggil saat penyemaian database, sehingga aturan validasi yang saya digunakan untuk (minlength 4 bukan default 6) tidak berlaku. Pastikan password anda (dan semua bidang lain dalam hal ini) adalah melewati validasi.
Ini adalah metode dasar pada Valin menjawab, saya telah menambahkan peran dalam db dan menambahkan password untuk user. Kode ini ditempatkan di Benih()
metode Migrasi>Konfigurasi.cs.
// role (Const.getRoles() return string[] whit all roles)
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
for (int i = 0; i < Const.getRoles().Length; i++)
{
if (RoleManager.RoleExists(Const.getRoles()[i]) == false)
{
RoleManager.Create(new IdentityRole(Const.getRoles()[i]));
}
}
// user
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var PasswordHash = new PasswordHasher();
if (!context.Users.Any(u => u.UserName == "[email protected]"))
{
var user = new ApplicationUser
{
UserName = "[email protected]",
Email = "[email protected]",
PasswordHash = PasswordHash.HashPassword("123456")
};
UserManager.Create(user);
UserManager.AddToRole(user.Id, Const.getRoles()[0]);
}
Di sini saya memiliki aplikasi yang sangat mudah,bersih dan halus solusi.
protected override void Seed(UserContext context)
{
//Step 1 Create the user.
var passwordHasher = new PasswordHasher();
var user = new IdentityUser("Administrator");
user.PasswordHash = passwordHasher.HashPassword("Admin12345");
user.SecurityStamp = Guid.NewGuid().ToString();
//Step 2 Create and add the new Role.
var roleToChoose = new IdentityRole("Admin");
context.Roles.Add(roleToChoose);
//Step 3 Create a role for a user
var role = new IdentityUserRole();
role.RoleId = roleToChoose.Id;
role.UserId = user.Id;
//Step 4 Add the role row and add the user to DB)
user.Roles.Add(role);
context.Users.Add(user);
}
Apa yang saya lakukan adalah membuat yang lain async yang tersedia dalam metode kedua dan menyebutnya serentak, bekerja sempurna bagi saya.
protected override void Seed(ApplicationDbContext context)
{
Task.Run(async () => { await SeedAsync(context); }).Wait();
}
private async Task SeedAsync(ApplicationDbContext context)
{
var userManager = new ApplicationUserManager(new UserStore<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context));
var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole, int, ApplicationUserRole>(context));
if (!roleManager.Roles.Any())
{
await roleManager.CreateAsync(new ApplicationRole { Name = ApplicationRole.AdminRoleName });
await roleManager.CreateAsync(new ApplicationRole { Name = ApplicationRole.AffiliateRoleName });
}
if (!userManager.Users.Any(u => u.UserName == "shimmy"))
{
var user = new ApplicationUser
{
UserName = "shimmy",
Email = "[email protected]",
EmailConfirmed = true,
PhoneNumber = "0123456789",
PhoneNumberConfirmed = true
};
await userManager.CreateAsync(user, "****");
await userManager.AddToRoleAsync(user.Id, ApplicationRole.AdminRoleName);
}
}
Sepertinya mereka mengubah cara otentikasi bekerja di MVC5, mengubah Global.asax.cs berikut melakukan trik!
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Threading.Tasks;
using MvcAuth.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Threading;
using Microsoft.AspNet.Identity.EntityFramework;
namespace MvcAuth
{
public class MvcApplication : System.Web.HttpApplication
{
async Task<bool> AddRoleAndUser()
{
AuthenticationIdentityManager IdentityManager = new AuthenticationIdentityManager(
new IdentityStore(new ApplicationDbContext()));
var role = new Role("Role1");
IdentityResult result = await IdentityManager.Roles.CreateRoleAsync(role, CancellationToken.None);
if (result.Success == false)
return false;
var user = new ApplicationUser() { UserName = "user1" };
result = await IdentityManager.Users.CreateLocalUserAsync(user, "Password1");
if (result.Success == false)
return false;
result = await IdentityManager.Roles.AddUserToRoleAsync(user.Id, role.Id, CancellationToken.None);
return result.Success;
}
protected async void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
bool x = await AddRoleAndUser();
}
}
}
tulis kode ini di Migrasi anda Konfigurasi.
catatan: Gunakan ApplicationDbContext dalam Konfigurasi Kelas.
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
context.Roles.AddOrUpdate(p =>
p.Id,
new IdentityRole { Name = "Admins"},
new IdentityRole { Name = "PowerUsers" },
new IdentityRole { Name = "Users" },
new IdentityRole { Name = "Anonymous" }
);
}
}