Click here to Skip to main content
15,850,103 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hello! I am trying to add a single moderator to my ASP.NET Core 2.0 website. All other users are going to be simple users except this one. So basically what I need is two roles, one called User, and one called Moderator. So far I came up with a solution, that comes up with a weird bug. The problem is that in the first await call (my method is asynchronous), the method doesn't do anything It seems to be stuck there, even though my website is getting launched successfully. If someone could help me with that, I would be glad.

What I have tried:

What I have done so far, is creating a method on the Startup class of my project, to create my roles. Then I call this method from the Configure method of the Startup class. This is the method:

private async Task CreateRoles(IServiceProvider serviceProvider)
{
    //Initialize role manager
    var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

    //We get if the moderator role already exists (This is exactly where the method is getting stuck)
    var moderatorRoleExists = await roleManager.RoleExistsAsync(Roles.Moderator);
    //We get if the user role already exists
    var userRoleExists = await roleManager.RoleExistsAsync(Roles.User);

    // if the moderator role doesn't exist
    if (!moderatorRoleExists)
    {
        //create the role and seed them to the database:
        await roleManager.CreateAsync(new IdentityRole(Roles.Moderator));
    }

    // if the moderator user doesn't exist
    if (!userRoleExists)
    {
        //create the role and seed them to the database:
        await roleManager.CreateAsync(new IdentityRole(Roles.User));
    }
}


And this is how I call it from the Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    CreateRoles(serviceProvider);
}
Posted
Updated 9-Sep-18 9:42am

1 solution

I actually managed to find a solution. The solution is to use the Wait method when calling the CreateRoles method. So the call, should be like that:

CreateRoles(serviceProvider).Wait();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900