System.InvalidOperationException:方案已经存在:Identity.Application:身份棚架之后

时间:2019-07-29 12:20:41

标签: c# asp.net-core asp.net-mvc-scaffolding

我现有一个ApplicationUser,并且想修改Login的UI页面。所以这就是为什么我决定执行脚手架操作的原因。

ApplicationUser.cs

public class ApplicationUser : IdentityUser
{
    public List<Student> Students { get; set; }
}

但是当我使用最后一个CLI命令时,这是这样的:

dotnet aspnet-codegenerator identity --files="Account.Login;"

我无法运行我的Web应用程序,这就是它在网络上显示的内容:

enter image description here

然后,这是在日志中发生的错误:

  

未处理的异常:System.InvalidOperationException:方案已   存在:Identity.Application位于   Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(String   名称,操作1 configureBuilder) at Microsoft.AspNetCore.Authentication.AuthenticationBuilder.<>c__DisplayClass4_0 2.b__0(AuthenticationOptions   o)在   Microsoft.Extensions.Options.ConfigureNamedOptions 1.Configure(String name, TOptions options) at Microsoft.Extensions.Options.OptionsFactory 1.Create(字符串名称)
  在   Microsoft.Extensions.Options.OptionsManager 1.<>c__DisplayClass5_0.<Get>b__0() at System.Lazy 1.ViaFactory(LazyThreadSafetyMode模式)位于   System.Lazy 1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy 1.CreateValue()位于   Microsoft.Extensions.Options.OptionsCache 1.GetOrAdd(String name, Func 1 createOptions)位于   Microsoft.Extensions.Options.OptionsManager 1.Get(String name) at Microsoft.Extensions.Options.OptionsManager 1.get_Value()在   Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions 1 options, IDictionary 2个方案)位于   Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions 1 options) --- End of stack trace from previous location where exception was thrown --- at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(IServiceCallSite   callSite,TArgument参数)在   Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite   scopedCallSite,ServiceProviderEngineScope范围)   Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite   singletonCallSite,ServiceProviderEngineScope范围)   Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite   callSite,TArgument参数)在   Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine。<> c__DisplayClass1_0.b__0(ServiceProviderEngineScope   范围)   Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type   serviceType,ServiceProviderEngineScope serviceProviderEngineScope)
  在   Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type   serviceType)在   Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type   serviceType)在   Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider   提供者)   Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider   提供者,类型为instanceType,Object []参数)位于   Microsoft.AspNetCore.Builder.UseMiddlewareExtensions。<> c__DisplayClass4_0.b__0(RequestDelegate   下一个)   Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()在   Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()在   Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken   cancelToken)   Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost主机,   CancellationToken令牌,字符串shutdownMessage)位于   Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost主机,   CancellationToken令牌)位于   Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost主机)
  在ICFERApp.Program.Main(String [] args)中   /Users/idrislutaaya/RiderProjects/ICFERApp/ICFERApp/Program.cs:第17行

我看过这个question,但对我没有帮助。

实际上让我感到惊讶的是,在下面的目录〜/ Areas / Identity / Data 中,有一个DBClass创建了它的自我:

enter image description here

public class ICFERAppIdentityDbContext : IdentityDbContext<IdentityUser>
{
    public ICFERAppIdentityDbContext(DbContextOptions<ICFERAppIdentityDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

但是我这里已有一个:

public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Student> Students { get; set; }

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

            builder.Entity<ApplicationUser>()
                .HasMany(s => s.Students)
                .WithOne(u => u.User);


            builder.Entity<Student>()
                .HasOne(e => e.Education)
                .WithOne(s => s.Student);


            builder.Entity<Student>()
                .HasOne(g => g.Guardian)
                .WithOne(s => s.Student);

            builder.Entity<Student>()
                .HasOne(p => p.Parents)
                .WithOne(s => s.Student);

            builder.Entity<Student>()
                .HasOne(s => s.Siblings)
                .WithOne(s => s.Student);

            builder.Entity<Siblings>()
                .Property(p => p.Id)
                .ValueGeneratedOnAdd();

            builder.Entity<Siblings>()
                .HasKey(x => new { x.Id, x.StudentId});

            builder.Entity<Education>()
                .Property(p => p.Id)
                .ValueGeneratedOnAdd();

            builder.Entity<Education>()
                .HasKey(x => new { x.Id, x.StudentId});


            builder.Entity<Guardian>()
                .Property(p => p.Id)
                .ValueGeneratedOnAdd();

            builder.Entity<Guardian>()
                .HasKey(x => new { x.Id, x.StudentId});
            builder.Entity<Parents>()
                .Property(p => p.Id)
                .ValueGeneratedOnAdd();

            builder.Entity<Parents>()
                .HasKey(x => new { x.Id, x.StudentId});


        }
    }

然后,在我的Startup.cs文件中,我遵循了Microsoft doc所说的:

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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

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

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


            services.AddTransient<IStudentRepository, StudentRepository>();
            services.AddMvc().AddNToastNotifyToastr();


            services.AddJsReport(new LocalReporting()
                .UseBinary(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    ? JsReportBinary.GetBinary()
                    : jsreport.Binary.OSX.JsReportBinary.GetBinary())
                .AsUtility()
                .Create());

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddRazorPagesOptions(options =>
                {
                    options.AllowAreas = true;
                    options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                    options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
                });

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = $"/Identity/Account/Login";
                options.LogoutPath = $"/Identity/Account/Logout";
                options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseNToastNotify();

            app.UseAuthentication();

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

利用以上所有信息,我的实现真正出了什么问题?

1 个答案:

答案 0 :(得分:1)

检查IdentityHostingStartup.cs并在退出时注释掉下面的行:

services.AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ICFERAppIdentityDbContext>();

简而言之,仅需要一种身份配置。 Here是相关的讨论。