text
stringlengths
0
13.4k
await userManager.AddToRoleAsync(
testAdmin, Constants.AdministratorRole);
}
If there isn't already a user with the username admin@todo.local in the
database, this method will create one and assign a temporary password.
After you log in for the first time, you should change the account's
password to something secure!
Next, you need to tell your application to run this logic when it starts up.
Modify Program.cs and update Main() to call a new method,
InitializeDatabase() :
Program.cs
public static void Main(string[] args)
{
var host = BuildWebHost(args);
InitializeDatabase(host);
host.Run();
}
Then, add the new method to the class below Main() :
private static void InitializeDatabase(IWebHost host)
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
SeedData.InitializeAsync(services).Wait();
}
92
Authorization with roles
catch (Exception ex)
{
var logger = services
.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Error occurred seeding the DB.");
}
}
}
Add this using statement to the top of the file:
using Microsoft.Extensions.DependencyInjection;
This method gets the service collection that SeedData.InitializeAsync()
needs and then runs the method to seed the database. If something goes
wrong, an error is logged.
Because InitializeAsync() returns a Task , the Wait() method
must be used to make sure it finishes before the application starts
up. You'd normally use await for this, but for technical reasons
you can't use await in the Program class. This is a rare
exception. You should use await everywhere else!
When you start the application next, the admin@todo.local account will
be created and assigned the Administrator role. Try logging in with this
account, and navigating to http://localhost:5000/ManageUsers . You'll