首页 > 解决方案 > InvalidOperationException:没有为方案“CookieSettings”注册身份验证处理程序

问题描述

我正在使用 ASP.Net MVC core 2.1 开发一个应用程序,我不断收到以下异常。

InvalidOperationException:没有为方案“CookieSettings”注册身份验证处理程序。注册的方案是:Identity.Application、Identity.External、Identity.TwoFactorRememberMe、Identity.TwoFactorUserId。你忘记调用 AddAuthentication().AddSomeAuthHandler 了吗?”

我浏览了文章,进行了必要的更改,但例外情况保持不变。我无法弄清楚下一步该做什么。

以下是我的 startup.cs :

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.AddDbContext<Infrastructure.Data.ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<Infrastructure.Data.ApplicationDbContext>();

        services.AddSingleton(Configuration);

        //Add application services.
       services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
        //Add services
        services.AddTransient<IContactManagement, ContactManagement>();
        services.AddTransient<IRepository<Contact>, Repository<Contact>>();
        services.AddTransient<IJobManagement, JobJobManagement>();
        services.AddTransient<IRepository<Job>, Repository<Job>>();
        services.AddTransient<IUnitManagement, UnitManagement>();
        services.AddTransient<IRepository<Sensor>, Repository<Sensor>>();
        services.AddTransient<IJobContactManagement, JobContactManagement>();
        services.AddTransient<IRepository<JobContact>, Repository<JobContact>>();
        services.AddTransient<IJobContactEventManagement, JobContactEventManagement>();
        services.AddTransient<IRepository<JobContactEvent>, Repository<JobContactEvent>>();
        services.AddTransient<IJobsensorManagement, JobsensorManagement>();
        services.AddTransient<IRepository<JobSensor>, Repository<JobSensor>>();
        services.AddTransient<IEventTypesManagement, EventTypesManagement>();
        services.AddTransient<IRepository<EventType>, Repository<EventType>>();
        services.AddTransient<IJobSensorLocationPlannedManagement, JobSensorLocationPlannedManagement>();
        services.AddTransient<IRepository<JobSensorLocationPlanned>, Repository<JobSensorLocationPlanned>>();
        services.AddTransient<IDataTypeManagement, DataTypeManagement>();
        services.AddTransient<IRepository<DataType>, Repository<DataType>>();
        services.AddTransient<IThresholdManegement, ThresholdManegement>();
        services.AddTransient<IRepository<Threshold>, Repository<Threshold>>();
        services.AddTransient<ISeverityTypeManagement, SeverityTypeManagement>();
        services.AddTransient<IRepository<SeverityType>, Repository<SeverityType>>();
        services.AddTransient<ISensorDataManagement, SensorDataManagement>();
        services.AddTransient<IRepository<SensorData>, Repository<SensorData>>();
        services.AddTransient<ISensorLocationManagement, SensorLocationManagement>();
        services.AddTransient<IRepository<SensorLocation>, Repository<SensorLocation>>();

        services.AddTransient<ISensorStatusTypeManagement, SensorStatusTypeManagement>();
        services.AddTransient<IRepository<SensorStatusType>, Repository<SensorStatusType>>();
        services.AddTransient<IRepository<SensorDataToday>, Repository<SensorDataToday>>();
        services.AddTransient<ISensorDataTodayManagement, SensorDataTodayManagement>();

        services.AddSession();


        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(20);
        });

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
               .AddCookie(options =>
               {
                   options.LoginPath = "/Account/Login/";
                   options.LogoutPath = "/Account/Logout/";
               });

        services.AddAuthentication(options =>
        {
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        });


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // 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");
            app.UseHsts();
        }

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

        app.UseAuthentication();

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

另外我想知道 AccountController 中是否需要进行任何更改?

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

解决方案


您的登录代码看起来像这样吗?

var claims = new[] 
{ 
    new Claim("name", authUser.Username)
};

var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

请参阅ASP.NET Core 中的详细信息 没有配置身份验证处理程序来处理方案 Cookie


推荐阅读