我已经创建了一个新的干净的asp.net 5项目(rc1-final).使用身份认证我只需要ApplicationDbContext.cs与以下代码:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { protected override void OnModelCreating(ModelBuilder builder) { // On event model creating base.OnModelCreating(builder); } }
请注意ApplicationDbContext使用IdentityDbContext而不是DbContext.
解决方法
我这样做的方法是在模型命名空间中创建一个类.
public class SampleData { public static void Initialize(IServiceProvider serviceProvider) { var context = serviceProvider.GetService<ApplicationDbContext>(); string[] roles = new string[] { "Owner","Administrator","Manager","Editor","Buyer","Business","Seller","Subscriber" }; foreach (string role in roles) { var roleStore = new RoleStore<IdentityRole>(context); if (!context.Roles.Any(r => r.Name == role)) { roleStore.CreateAsync(new IdentityRole(role)); } } var user = new ApplicationUser { FirstName = "Muhammad",LastName = "Abdullah",Email = "abdullahnaseer999@gmail.com",normalizedEmail = "ABDULLAHNASEER999@GMAIL.COM",UserName = "Owner",normalizedUserName = "OWNER",PhoneNumber = "+923366633352",EmailConfirmed = true,PhoneNumberConfirmed = true,SecurityStamp = Guid.NewGuid().ToString("D") }; if (!context.Users.Any(u => u.UserName == user.UserName)) { var password = new PasswordHasher<ApplicationUser>(); var hashed = password.HashPassword(user,"secret"); user.PasswordHash = hashed; var userStore = new UserStore<ApplicationUser>(context); var result = userStore.CreateAsync(user); } AssignRoles(serviceProvider,user.Email,roles); context.SaveChangesAsync(); } public static async Task<IdentityResult> AssignRoles(IServiceProvider services,string email,string[] roles) { UserManager<ApplicationUser> _userManager = services.GetService<UserManager<ApplicationUser>>(); ApplicationUser user = await _userManager.FindByEmailAsync(email); var result = await _userManager.AddToRolesAsync(user,roles); return result; } }
在启动时运行此代码.在Startup.cs的配置方法结束后,路由配置后添加以下代码作为Stafford Williams说.
SampleData.Initialize(app.applicationservices);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。