C# InvalidOperationException:没有配置IAAuthenticationSignInHandler来处理方案的登录:MyCookieAuthenticationScheme

C# InvalidOperationException:没有配置IAAuthenticationSignInHandler来处理方案的登录:MyCookieAuthenticationScheme,c#,.net-core-2.0,asp.net-core-mvc-2.0,C#,.net Core 2.0,Asp.net Core Mvc 2.0,我正在尝试按照说明将Cookie身份验证添加到我的站点 到目前为止,我添加了以下内容: 在的Configure方法中调用UseAuthentication方法 Startup.cs文件: 在中调用AddAuthentication和AddCookie方法 Startup.cs文件的ConfigureServices方法: 在我的登录代码中,我有 await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal); 原

我正在尝试按照说明将Cookie身份验证添加到我的站点

到目前为止,我添加了以下内容:

在的Configure方法中调用UseAuthentication方法 Startup.cs文件:

在中调用AddAuthentication和AddCookie方法 Startup.cs文件的ConfigureServices方法:

在我的登录代码中,我有

await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal);
原则
是一项
原则

当我登录到我的站点并调用上面的线路时,我得到错误:

InvalidOperationException:未启用IAAuthenticationSignInHandler 配置为处理方案的登录: mycokie认证方案


我遗漏了什么?

您说过希望默认方案为“MyOkieAuthenticationScheme”(这是
AddAuthentication
的第一个参数),但您没有添加具有该名称的身份验证处理程序。当您调用
AddCookies
时,您添加了带有方案“Cookies”的处理程序(这是默认设置)

您需要将代码更改为:

services.AddAuthentication("MyCookieAuthenticationScheme")
    .AddCookie("MyCookieAuthenticationScheme", options => 
    {
        options.AccessDeniedPath = "/Account/Forbidden/";
        options.LoginPath = "/Account/Unauthorized/";
    });
请参阅本文以更好地理解原语:


尝试更改呼叫地点
服务。添加身份验证(
这对我很有帮助

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    ...
    var builder = new ContainerBuilder();
    builder.RegisterModule(new HowResolveDependencies());

    services.AddTransient<IExceptionHandler, ExceptionToResponseWriter>();

    builder.Populate(services);

    services.AddAuthentication(AuthConsts.MainAuthScheme)
                 .AddCookie(
    ...
}
公共IServiceProvider配置服务(IServiceCollection服务)
{
...
var builder=new ContainerBuilder();
RegisterModule(新的howsolveDependencies());
services.AddTransient();
建造商。填充(服务);
services.AddAuthentication(AuthConsts.MainAuthScheme)
.AddCookie(
...
}

在我的项目中,将
services.AddAuthentication
放在
builder.Populate(services)
之前解决了这个问题。

谢谢!我一天中大部分时间都在尝试解决这个问题。有很多示例,但它们忽略了身份验证处理程序。
services.AddAuthentication("MyCookieAuthenticationScheme")
    .AddCookie("MyCookieAuthenticationScheme", options => 
    {
        options.AccessDeniedPath = "/Account/Forbidden/";
        options.LoginPath = "/Account/Unauthorized/";
    });
public IServiceProvider ConfigureServices(IServiceCollection services)
{
    ...
    var builder = new ContainerBuilder();
    builder.RegisterModule(new HowResolveDependencies());

    services.AddTransient<IExceptionHandler, ExceptionToResponseWriter>();

    builder.Populate(services);

    services.AddAuthentication(AuthConsts.MainAuthScheme)
                 .AddCookie(
    ...
}