C# 修改CookieAuthenticationOptions登录路径OnRedirectToReturnUrl事件

C# 修改CookieAuthenticationOptions登录路径OnRedirectToReturnUrl事件,c#,asp.net-mvc,authentication,asp.net-core,asp.net-core-mvc,C#,Asp.net Mvc,Authentication,Asp.net Core,Asp.net Core Mvc,我的MVC 6 ASP.NET 5项目中有以下设置: Configure方法中的Startup.cs: app.UseCookieAuthentication(options => { options.AuthenticationScheme = "Cookie"; options.LoginPath = new PathString("/<TENANT>/account/signin/"); options.AccessDeniedPath = new

我的MVC 6 ASP.NET 5项目中有以下设置:

Configure方法中的Startup.cs:

app.UseCookieAuthentication(options =>
{
    options.AuthenticationScheme = "Cookie";
    options.LoginPath = new PathString("/<TENANT>/account/signin/");
    options.AccessDeniedPath = new PathString("/<TENANT>/account/unauthorised/");
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;
    options.Events = new CookieAuthenticationEvents
    {
        OnRedirectToReturnUrl = MyClass.RedirectToReturnUrlAsync
    };
});
我希望Cookie中间件将用户重定向到:

http://localhost/mycompany/account/signin
问题是,当重定向到返回Url时,代码“MyClass.RedirectToReturnUrlAsync”从未被命中,因此我找不到在运行时修改LoginPath的机会

我怀疑我的设置有问题。有人遇到过这个问题吗


好极了,我想我明白了。我从一个错误的角度看待这个问题(在一次睡眠之后!)

app.UseCookieAuthentication(选项=>
{
options.AuthenticationScheme=“Cookie”;
options.LoginPath=新路径字符串(“//account/signin/”);
options.AccessDeniedPath=新路径字符串(“//account/unauthorized/”;
options.AutomaticAuthenticate=true;
options.AutomaticChallenge=true;
options.Events=new mycokieeauthenticationevents();
});
创建您自己的自定义Cookie身份验证事件的正确方法是从CookieAuthenticationEvents对象派生并覆盖您想要自定义的事件,如下所示:

public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
    public override Task RedirectToLogin(CookieRedirectContext context)
    {
        context.RedirectUri = <PUT LOGIC HERE TO REPLACE YOUR REDIRECT URI>
        return base.RedirectToLogin(context);
    }
}
公共类MyCookieAuthenticationEvents:CookieAuthenticationEvents
{
公共覆盖任务重定向到登录(CookiierRedirectContext上下文)
{
context.RedirectUri=
返回base.RedirectToLogin(上下文);
}
}
在我之前的尝试中,我也瞄准了错误的事件。在我的例子中,正确的重写方法是“RedirectToLogin”方法

胡鲁

http://localhost/mycompany/account/signin
app.UseCookieAuthentication(options =>
{
    options.AuthenticationScheme = "Cookie";
    options.LoginPath = new PathString("/<TENANT>/account/signin/");
    options.AccessDeniedPath = new PathString("/<TENANT>/account/unauthorised/");
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;
    options.Events = new MyCookieAuthenticationEvents();
});
public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
    public override Task RedirectToLogin(CookieRedirectContext context)
    {
        context.RedirectUri = <PUT LOGIC HERE TO REPLACE YOUR REDIRECT URI>
        return base.RedirectToLogin(context);
    }
}