仅当我从Startup.cs中的Configure调用扩展方法SeedDatabase时,才收到此错误。如果我对那条线发表评论,一切都会很好。
这是Startup.cs中的Configure方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.SeedDatabase(); // if comment this works!
}
有一个带有SeedDatabase方法的IApplicationBuilder扩展类。
public static class ApplicationBuilderExtensions
{
private const string DefaultAdminEmail = "admin@gmail.com";
private const string DefaultAdminPassword = "admin";
private const string DefaultUserEmail = "user@gmail.com";
private const string DefaultUserPassword = "user";
private static readonly IdentityRole[] defaultRoles = new IdentityRole[]
{
new IdentityRole(RoleName.Admin),
new IdentityRole(RoleName.Member),
};
public static async void SeedDatabase(this IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<User>>();
var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
await SeedRoles(roleManager);
await SeedUsers(userManager, roleManager);
}
}
private static async Task SeedRoles(RoleManager<IdentityRole> roleManager)
{
foreach (var role in defaultRoles)
{
var roleExist = await roleManager.RoleExistsAsync(role.Name);
if (!roleExist)
{
await roleManager.CreateAsync(role);
}
}
}
private static async Task SeedUsers(UserManager<User> userManager, RoleManager<IdentityRole> roleManager)
{
var adminUser = await userManager.FindByEmailAsync(DefaultAdminEmail);
var memberUser = await userManager.FindByEmailAsync(DefaultUserEmail);
if (adminUser == null)
{
adminUser = new User()
{
UserName = DefaultAdminEmail,
Email = DefaultAdminEmail
};
await userManager.CreateAsync(adminUser, DefaultAdminPassword);
}
if (memberUser == null)
{
memberUser = new User()
{
UserName = DefaultUserEmail,
Email = DefaultUserEmail
};
await userManager.CreateAsync(memberUser, DefaultUserPassword);
}
await userManager.AddToRoleAsync(adminUser, RoleName.Admin);
await userManager.AddToRoleAsync(memberUser, RoleName.Member);
}
}
答案 0 :(得分:0)
确保在防火墙上打开了端口44311,看来它无法访问数据库
还必须调试并检查错误
这是查看您如何调试的链接 https://docs.microsoft.com/en-us/aspnet/core/migration/index?view=aspnetcore-2.1