c# - 启动应用程序时发生错误。 InvalidOperationException : Scheme already exists: Identity. 应用程序

标签 c# asp.net-core jwt asp.net-identity

An error occurred while starting the application.
InvalidOperationException: Scheme already exists: Identity.Application Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(string name, Action 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,但不幸的是它会产生以下错误

An error occurred while starting the application.
InvalidOperationException: Scheme already exists: Identity.Application Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(string name, Action configureBuilder)
InvalidOperationException: Scheme already exists: Identity.Application Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(string name, Action configureBuilder) Microsoft.AspNetCore.Authentication.AuthenticationBuilder+<>c__DisplayClass4_0.b__0(AuthenticationOptions o) Microsoft.Extensions.Options.ConfigureNamedOptions.Configure(string name, TOptions options) Microsoft.Extensions.Options.OptionsFactory.Create(string name) Microsoft.Extensions.Options.OptionsManager+<>c__DisplayClass5_0.b__0() System.Lazy.ViaFactory(LazyThreadSafetyMode mode) System.Lazy.ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor) System.Lazy.CreateValue() Microsoft.Extensions.Options.OptionsCache.GetOrAdd(string name, Func createOptions) Microsoft.Extensions.Options.OptionsManager.Get(string name) Microsoft.Extensions.Options.OptionsManager.get_Value() Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions options, IDictionary schemes) Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions options) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(IServiceCallSite callSite, TArgument argument) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(IServiceCallSite callSite, TArgument argument) Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass1_0.b__0(ServiceProviderEngineScope scope) 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 provider) Microsoft.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()

最佳答案

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

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

我添加了此代码而不是以下代码

services.AddIdentity<IdentityUser, IdentityRole>()

.AddEntityFrameworkStores() .AddDefaultTokenProviders();

这对我来说只用了 5-6 个小时就有效。

谢谢 马赫什·萨布尼斯

关于c# - 启动应用程序时发生错误。 InvalidOperationException : Scheme already exists: Identity. 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55951717/

相关文章:

c# - 在 WPF 文本框上调用 Select() 不执行任何操作

c# - 为什么在尝试获取每个进程的 CPU 使用率时出现异常?

c# - 专门针对旧版本的单个 .NET Standard API/命名空间(Entity Framework Core)

rest - JWT 用于无状态 API,但 session 控制用于安全

c# - .NET WebApi如何防止 "$ref": "x" output of JSON

c# - 如何从 Xamarin.Forms 中的可移植类库项目调用位于 Android 项目内部的方法?

c# - 从以 id 作为外键的表中加载对象

c# - 在 Swagger 中添加多个 header 值

javascript - Node :Error 401(Unauthorized) i m using passport-jwt

javascript - 使用 Axios post 请求进行 JWT 授权