InvalidOperationException:方案已存在:Identity.Application

InvalidOperationException: Scheme already exists: Identity.Application

我已经尝试了 中的解决方案,但没有成功。

在我的 Startup.cs 我有这个:

services.AddDbContext<ApplicationDbContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

//services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = true)
//    .AddRoles<ApplicationRole>()
//    .AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentity<ApplicationUser, ApplicationRole>()
    .AddRoles<ApplicationRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

services.Configure<IdentityOptions>(options =>
{
    options.SignIn.RequireConfirmedAccount = true;
    options.Password.RequiredLength = 8;
    options.Password.RequireDigit = false;
    options.Password.RequireUppercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequiredUniqueChars = 5;
    options.Lockout.MaxFailedAccessAttempts = 3;
    options.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 15, 0); // 15 minutes
});

我尝试从我的解决方案中删除文件 IdentityHostingStartup.cs,但没有任何区别。现在我已经把它加回来了(在 Areas/Identity/Pages 中),但注释掉了我认为造成问题的地方:

//[assembly: HostingStartup(typeof(MyAppName.Areas.Identity.IdentityHostingStartup))]
namespace MyAppName.Areas.Identity
{
    public class IdentityHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            //builder.ConfigureServices((context, services) => {
            //    services.AddDbContext<ApplicationDbContext>(options =>
            //        options.UseSqlServer(
            //            context.Configuration.GetConnectionString("GroupManagerContextConnection")));

            //services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            //    .AddEntityFrameworkStores<ApplicationDbContext>();
            //});
        }
    }
}

此 ASP Identity Core InvalidOperationException 主要在 Startup.cs 中存在对函数的重复调用时抛出。现在请看你的代码 services.AddIdentity<ApplicationUser, ApplicationRole>() .AddRoles<ApplicationRole>() 我想你在这里调用了角色二 times.for 你发现这个 exception.you 应该使用 :-

services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
            

services.AddIdentity<ApplicationUser>()
    .AddRoles<ApplicationRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

所以,上面我描述了你的主要问题。

现在您可以尝试这样的操作:-

public class ApplicationUser : IdentityUser
{
    //clarify code
}

Startup.cs

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();