C# InvalidOperationException:没有为方案注册身份验证处理程序';CookieSettings';。您忘记调用AddAuthentication()了吗

C# InvalidOperationException:没有为方案注册身份验证处理程序';CookieSettings';。您忘记调用AddAuthentication()了吗,c#,C#,我正在使用ASP.NETMVCCore2.1开发一个应用程序,在这个应用程序中,我不断遇到以下异常 InvalidOperationException:没有为方案“CookieSettings”注册身份验证处理程序。注册的方案为:Identity.Application、Identity.External、Identity.TwoFactorMemberMe、Identity.TwoFactorUserId。是否忘记调用AddAuthentication().AddSomeAuthHandler

我正在使用ASP.NETMVCCore2.1开发一个应用程序,在这个应用程序中,我不断遇到以下异常

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

我浏览了一些文章,做了必要的修改,但例外情况仍然是一样的。我不知道下一步该怎么办

以下是我的启动。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?}");
    });
}
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。使用此方法向容器中添加服务。
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
services.AddDbContext(选项=>
options.UseSqlServer(
GetConnectionString(“DefaultConnection”);
services.AddDefaultIdentity()
.AddEntityFrameworkStores();
services.AddSingleton(配置);
//添加应用程序服务。
services.AddTransient();
services.AddTransient();
//添加服务
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddSession();
services.AddSession(选项=>
{
options.IdleTimeout=TimeSpan.FromMinutes(20);
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(选项=>
{
options.LoginPath=“/Account/Login/”;
options.LogoutPath=“/Account/Logout/”;
});
services.AddAuthentication(选项=>
{
options.defaultsignnscheme=CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme=CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}
登录/signin.cs:

public async Task<IActionResult> Login(LoginViewModel model, ApplicationUser applicationUser, string returnUrl = "/RealTimeChart/Index")
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            ApplicationUser signedUser = await _userManager.FindByEmailAsync(model.Email);
            if (signedUser != null)
            {
                var result = await _signInManager.PasswordSignInAsync(signedUser.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    //Authorize login user
                    if (!string.IsNullOrEmpty(signedUser.UserName))
                    {
                        await AuthorizeUser(signedUser);
                    }
                    _logger.LogInformation(1, "User logged in.");
                    HttpContext.Session.SetString("UserName", model.Email);
                    int AccountTypeId = _contactManagement.GetContactDetailsByUserId(signedUser.Id).UserAccountTypeId;
                    HttpContext.Session.SetString("AccountTypeId", AccountTypeId.ToString());
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    if (_userManager.SupportsUserLockout && await _userManager.GetLockoutEnabledAsync(signedUser))
                    {
                        await _userManager.AccessFailedAsync(signedUser);
                    }
                }

                if (result.RequiresTwoFactor)
                {
                    return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                }
                if (signedUser.LockoutEnd != null)
                {
                    _logger.LogWarning(2, "User account locked out.");
                    return View("Lockout");
                }
                else
                {
                    ViewBag.InvalidPassword = "Password is Invalid";
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return View(model);
                }
            }
            else
            {
                ViewBag.InvalidEmail = "Email  is Invalid";
                return View(model);
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }
public异步任务登录(LoginViewModel模型,ApplicationUser ApplicationUser,string returnUrl=“/RealTimeChart/Index”)
{
ViewData[“ReturnUrl”]=ReturnUrl;
if(ModelState.IsValid)
{
//这不会将登录失败计入帐户锁定
//要启用密码故障触发帐户锁定,请设置lockoutOnFailure:true
ApplicationUser signedUser=await_userManager.FindByEmailAsync(model.Email);
if(signedUser!=null)
{
var result=wait _signInManager.PasswordSignInAsync(signedUser.UserName、model.Password、model.RememberMe、lockoutOnFailure:false);
if(result.successed)
{
//授权登录用户
如果(!string.IsNullOrEmpty(signedUser.UserName))
{
等待授权用户(signedUser);
}
_logger.LogInformation(1,“用户登录”);
HttpContext.Session.SetString(“用户名”,model.Email);
int AccountTypeId=\u contactManagement.getcontactDetailsBySerid(signedUser.Id).UserAccountTypeId;
HttpContext.Session.SetString(“AccountTypeId”,AccountTypeId.ToString());
返回重定向到本地(returnUrl);
}
其他的
{
if(_userManager.SupportsUserLockout&&wait_userManager.GetLockoutEnabledAsync(signedUser))
{
wait_userManager.AccessFailedAsync(signedUser);
}
}
if(结果要求系数)
{
return RedirectToAction(nameof(SendCode),new{ReturnUrl=ReturnUrl,RememberMe=model.RememberMe});
}
if(signedUser.LockoutEnd!=null)
{
List<Claim> userClaims = new List<Claim>
                        {
                            new Claim(applicationUser.Id, Convert.ToString(applicationUser.Id)),
                            new Claim(ClaimTypes.Name, applicationUser.UserName),
                            new Claim(ClaimTypes.Role, Convert.ToString(applicationUser.Id))
                        };

        var identity = new ClaimsIdentity(userClaims, CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(identity));
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                o.Cookie.Name = options.CookieName;
                o.Cookie.Domain = options.CookieDomain;
                o.SlidingExpiration = true;
                o.ExpireTimeSpan = options.CookieLifetime;
                o.TicketDataFormat = ticketFormat;
                o.CookieManager = new CustomChunkingCookieManager();
            });