c# - Create Users and Roles in ASP.NET 6 & Entity Framework 7 -
i need create users , roles @ first startup of web application. that, write code configure()
function in startup.cs
.
when run application, error:
an exception of type 'system.aggregateexception' occurred in mscorlib.dll not handled in user code @ call of first function "createusers"
code:
public async void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory, iserviceprovider serviceprovider, applicationdbcontext context) { ... await createusers(context, serviceprovider); await createroles(context, serviceprovider); } private async task createusers(applicationdbcontext context, iserviceprovider serviceprovider) { list<applicationuser> users = new list<applicationuser>(); users.add(new applicationuser { username = "devuser", email = "dev@dev.com", lastname = "dev", firstname = "dev", passwordhash = "devpassword" }); users.add(new applicationuser { username = "workuser", email = "work@work.com", lastname = "work", firstname = "work", passwordhash = "workpassword" }); foreach(var user in users) { var userexist = await _usermanager.findbyemailasync(user.email); if(userexist != null) { await _usermanager.createasync(user, user.passwordhash); context.users.add(user); context.savechanges(); } } } private async task createroles(applicationdbcontext context, iserviceprovider serviceprovider) { var usermanager = serviceprovider.getrequiredservice<usermanager<applicationuser>>(); var rolemanager = serviceprovider.getrequiredservice<rolemanager<identityrole>>(); list<identityrole> roles = new list<identityrole>(); roles.add(new identityrole { name = "developer", normalizedname = "developer" }); roles.add(new identityrole { name = "work", normalizedname = "work" }); roles.add(new identityrole { name = "admin", normalizedname = "admin" }); roles.add(new identityrole { name = "redacteur", normalizedname = "redacteur" }); roles.add(new identityrole { name = "correcteur", normalizedname = "correcteur" }); roles.add(new identityrole { name = "membre", normalizedname = "membre" }); foreach(var role in roles) { var roleexist = await rolemanager.roleexistsasync(role.name); if(!roleexist) { context.roles.add(role); context.savechanges(); } } var devuser = await usermanager.findbyemailasync("dev@dev.com"); await usermanager.addtoroleasync(devuser, "developer"); var work = await usermanager.findbyemailasync("work@work.com"); await usermanager.addtoroleasync(work, "work"); }
Comments
Post a Comment