学无先后达者为师!
不忘初心,砥砺前行。

ASP.NET CORE 动态设置登录重定向地址

在多语言或者允许多身份登录的系统中,我们可能需要根据不同的情况将未登录的用户重定向到不同的登录页面。在一个多语言网站中,法语的登录页面可能位于

/fr-fr/account/login
/fr-fr/account/login 而英语的登录页面可能位于另一个地址
/en-us/account/login
/en-us/account/login

在 ASP.NET CORE 中,可以通过重写

CookieAuthenticationEvents
CookieAuthenticationEvents
RedirectToLogin
RedirectToLogin 来实现上述功能。当然,前提是你使用的就是
CookieAuthentication
CookieAuthentication

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class MyCookieAuthenticationEvents : CookieAuthenticationEvents, IScopedDependency
{
public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
{
context.RedirectUri = $"";//在这里写你需要自定义跳转的登录地址即可
return base.RedirectToLogin(context);
}
}
public class MyCookieAuthenticationEvents : CookieAuthenticationEvents, IScopedDependency { public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context) { context.RedirectUri = $"";//在这里写你需要自定义跳转的登录地址即可 return base.RedirectToLogin(context); } }
public class MyCookieAuthenticationEvents : CookieAuthenticationEvents, IScopedDependency
{
    public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
    {
		context.RedirectUri = $"";//在这里写你需要自定义跳转的登录地址即可
        return base.RedirectToLogin(context);
    }
}

类型创建好之后要先注册,接着配置

AuthenticationSchemeOptions
AuthenticationSchemeOptions
EventsType
EventsType 为上述类型即可:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
services.AddAuthentication()
.AddCookie(options => {
options.EventsType = typeof(MyCookieAuthenticationEvents);
}
);
services.AddAuthentication() .AddCookie(options => { options.EventsType = typeof(MyCookieAuthenticationEvents); } );
services.AddAuthentication()
    .AddCookie(options => {
        options.EventsType = typeof(MyCookieAuthenticationEvents);
        }
    );

赞(1) 打赏
未经允许不得转载:码农很忙 » ASP.NET CORE 动态设置登录重定向地址

评论 抢沙发

给作者买杯咖啡

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册