我正在尝试为我的项目设置一个管理员用户ID。我选择在startup.cs程序中执行此操作。我在startup.cs中添加了一个名为CreateUsersAndRoles的种子方法。
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("admin@aserver.net");
if (user == null)
{
user = new IdentityUser()
{
UserName = "admin@aserver.net",
Email = "admin@aserver.net",
};
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();
}
}
}
我已经调试了程序,并且错误在种子方法的以下行发生:
此相同代码在同一台计算机上的另一个项目中成功执行,因此我认为它可能与我的项目规范有关。我尝试了各种版本的csproj文件,但所有这些都导致了相同的错误。
我正在使用ASP.NET Core 2.1。
这是我的* .csproj文件:
<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>
答案 0 :(得分:1)
您的ApplicationDbContext类是什么样的?
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
也许您也可以尝试以此编辑启动文件吗?
services.AddDefaultIdentity<ApplicationUser>()
答案 1 :(得分:0)
尝试使用此ApplicationDbContext。这可能会解决您的问题。
public class ApplicationDbContext : IdentityDbContext<IdentityUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}