在多语言或者允许多身份登录的系统中,我们可能需要根据不同的情况将未登录的用户重定向到不同的登录页面。在一个多语言网站中,法语的登录页面可能位于
/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
。
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
为上述类型即可:
services.AddAuthentication()
.AddCookie(options => {
options.EventsType = typeof(MyCookieAuthenticationEvents);
}
);
services.AddAuthentication()
.AddCookie(options => {
options.EventsType = typeof(MyCookieAuthenticationEvents);
}
);
services.AddAuthentication() .AddCookie(options => { options.EventsType = typeof(MyCookieAuthenticationEvents); } );