首页 > 解决方案 > 启动应用程序时发生错误。InvalidOperationException:方案已存在:Identity.Application

问题描述

启动应用程序时发生错误。
InvalidOperationException:方案已存在:Identity.Application Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(字符串名称,操作 configureBuilder)

我正在使用 VS 2017 中的 Angular 模板开发 ASP.NET Core WEB API。我在 Statrtup.cs 类的 ConfigureServices() 方法中有以下代码

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AuthDbContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("AuthDbContextConnection"));
    });

    services.AddDbContext<AppNgDbContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("AppNgDbContextConnection"));
    });

    services.AddTransient<SecurityService>();

    services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<AuthDbContext>()
            .AddDefaultTokenProviders();

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                // 1. Load the JST Secret Key to Verify and Validate Token
                // read key from appsettings.json
                var secretKey = Convert.FromBase64String(Configuration["JWTAppSettings:SecretKey"]);
                // 2. Defining the Mechanism for Validating Received Token from Client
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(secretKey)
                };
            });

    services.AddScoped<IRepository<Orders, int>, OrdersRepository>();

    services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    // In production, the Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });
}

当我运行应用程序时,它应该加载以便我可以访问 WEB API 但不幸的是它会产生以下错误

启动应用程序时发生错误。
InvalidOperationException:方案已存在:Identity.Application Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(字符串名称,操作 configureBuilder)
InvalidOperationException:方案已存在:Identity.Application Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(字符串名称,操作 configureBuilder)Microsoft.AspNetCore.Authentication.AuthenticationBuilder+<>c__DisplayClass4_0.b__0(AuthenticationOptions o)Microsoft.Extensions.Options.ConfigureNamedOptions.Configure (字符串名称,TOptions 选项) Microsoft.Extensions.Options.OptionsFactory.Create(字符串名称) Microsoft.Extensions.Options.OptionsManager+<>c__DisplayClass5_0.b__0() System.Lazy.ViaFactory(LazyThreadSafetyMode 模式) System.Lazy.ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor) System.Lazy.CreateValue() Microsoft.Extensions.Options.OptionsCache.GetOrAdd(string name, Func createOptions) Microsoft.Extensions.Options.OptionsManager。Get(字符串名称) Microsoft.Extensions.Options.OptionsManager.get_Value() Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions 选项,IDictionary 方案) Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions 选项) Microsoft.Extensions .DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite 构造函数CallSite,ServiceProviderEngineScope 范围)Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(IServiceCallSite callSite,TArgument 参数)Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedEngineSite 服务范围调用范围提供程序) ) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver。VisitSingleton(SingletonCallSite singletonCallSite,ServiceProviderEngineScope 范围)Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(IServiceCallSite callSite,TArgument 参数)Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass1_0.b__0(ServiceProviderEngineScope 范围)Microsoft.Extensions.DependencyInjection。 ServiceLookup.ServiceProviderEngine.GetService(类型 serviceType,ServiceProviderEngineScope serviceProviderEngineScope)Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(类型 serviceType)Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(类型 serviceType)Microsoft.Extensions.Internal.ActivatorUtilities+ConstructorMatcher。 CreateInstance(IServiceProvider 提供程序)微软。Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, object[] parameters) Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass4_0.b__0(RequestDelegate next) Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build() Microsoft. AspNetCore.Hosting.Internal.WebHost.BuildApplication()

标签: c#asp.net-corejwtasp.net-identity

解决方案


做了一些尝试后,我发现以下几行对我有用

  services.AddIdentityCore<IdentityUser>().AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<AuthDbContext>()
            .AddDefaultTokenProviders();

我添加了这个而不是下面的代码

services.AddIdentity<IdentityUser, IdentityRole>()

.AddEntityFrameworkStores() .AddDefaultTokenProviders();

仅使用完整的 5-6 小时后,这对我有用。

谢谢马赫什萨尼斯


推荐阅读