0

I am trying to set up an admin user id to my project. I chose to do this in the startup.cs program. I have added a seed method named CreateUsersAndRoles into startup.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using sbingP3.Data;
using sbingP3.Models;
using sbingP3.Services;
using Microsoft.AspNetCore.Mvc;

namespace sbingP3
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //Core 2.1
            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddDefaultUI()
                .AddDefaultTokenProviders()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); ;
        }

        private async Task CreateUsersAndRoles(IServiceProvider serviceProvider)
        {
            //Get reference to RoleManager and UserManager from serviceProvider through dependency injection
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();

            //Check if admin role exists and if not add it.
            var roleExist = await RoleManager.RoleExistsAsync("Admin");
            if (!roleExist)
            {
                //create the roles and seed them to the database: Question 1  
                await RoleManager.CreateAsync(new IdentityRole("Admin"));
            }

            //Check if admin user exists and if not add it
            IdentityUser user = await UserManager.FindByEmailAsync("[email protected]");

            if (user == null)
            {
                user = new IdentityUser()
                {
                    UserName = "[email protected]",
                    Email = "[email protected]",
                };
                await UserManager.CreateAsync(user, "Password1!");

                //Add user to admin role
                await UserManager.AddToRoleAsync(user, "Admin");
            }
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        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?}");
            });

            CreateUsersAndRoles(serviceProvider).Wait();
        }
    }
}

I have debugged the program and the error occurs at the following line in my seed method:

This identical code executes successfully in another project on the same machine, so I figured that it might have something to do with my project specifications. I tried various versions of the csproj file, but all of them resulted in the same error.

I am using ASP.NET Core 2.1.

here is my *.csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <UserSecretsId></UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="bootstrap" Version="4.1.3" />
    <PackageReference Include="bootstrap.sass" Version="4.1.3" />
    <PackageReference Include="MailKit" Version="2.0.6" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.4" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.5" />
  </ItemGroup>

</Project>
1
  • The program aborts at this line in the CreateUsersAndRoles task: IdentityUser user = await UserManager.FindByEmailAsync("[email protected]"); Commented Oct 25, 2018 at 19:41

2 Answers 2

1

What does your ApplicationDbContext class look like?

public class ApplicationDbContext : IdentityDbContext<IdentityUser>

also maybe you can try to edit your startup file with this?

services.AddDefaultIdentity<ApplicationUser>()
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use this ApplicationDbContext. this might solve your problem.

public class ApplicationDbContext : IdentityDbContext<IdentityUser, IdentityRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.