请尝试一下,如果有任何问题请告诉我。
我启动了一个新的asp.net core web应用程序,使用"个人用户帐户"模板进行授权。似乎EF的所有配置都发生在Startup.cs
中services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
但我找不到任何例子,或文档如何添加一个
我是这样做到的。我在DBContext类的扩展类中创建了一个seed方法,并在startup类的configure方法中调用它。
public static class CrmContextExtension
{
public static async Task SeedDataForContext(this CrmContext context)
{
// if there is no role exist then create some default role 'administrator'
var logger = LogManager.GetCurrentClassLogger();
if (context.Roles.Count() == 0)
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store,null, null, null, null,null);
var role = new IdentityRole { Name = "administrator" };
IdentityResult result = await manager.CreateAsync(role);
logger.Info(result.Succeeded ? "Role 'administrator' has been successfully created" :
"Couldn't create role 'administrator' in the seed.");
}
}
}
public async void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, CrmContext context)
{ ......
await context.SeedDataForContext();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}