MVC Core 3.0 options.LoginPath - 添加本地化路由参数
MVC Core 3.0 options.LoginPath - add localization route parameter
我在 Startup - ConfigureServices 中有以下代码:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/en/Authentication/LogIn");
});
一切正常,但我找不到使用 URL 参数(en/de/es 等)使 LoginPath 可本地化的方法
我的 MapControllerRoute 看起来像:
"{lang}/{controller=Home}/{action=Index}/{id?}"
是否可以重定向到适当的 lang 进行身份验证,就像用户正在访问 /de/NeedAuth/Index - 它应该重定向到 /de/Authentication/LogIn?
好的。我花了一个小时,这是一个解决方案 - 以防有人有类似的用例。
第一步:
创建一个新的 class 来动态获取当前的 http 请求以确定重定向:
public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
{
var httpContext = context.HttpContext;
var routePrefix = httpContext.GetRouteValue("lang");
context.RedirectUri = $"/{routePrefix.ToString()}/Authentication/LogIn";
return base.RedirectToLogin(context);
}
}
第 2 步:
在 Startup 中修改与重定向到认证页面相关的 cookie 认证声明:
services.AddScoped<CustomCookieAuthenticationEvents>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/Authentication/LogIn");
options.EventsType = typeof(CustomCookieAuthenticationEvents);
});
注意将CustomCookieAuthenticationEvents注册为上面的服务
我在 Startup - ConfigureServices 中有以下代码:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/en/Authentication/LogIn");
});
一切正常,但我找不到使用 URL 参数(en/de/es 等)使 LoginPath 可本地化的方法
我的 MapControllerRoute 看起来像:
"{lang}/{controller=Home}/{action=Index}/{id?}"
是否可以重定向到适当的 lang 进行身份验证,就像用户正在访问 /de/NeedAuth/Index - 它应该重定向到 /de/Authentication/LogIn?
好的。我花了一个小时,这是一个解决方案 - 以防有人有类似的用例。
第一步: 创建一个新的 class 来动态获取当前的 http 请求以确定重定向:
public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
{
var httpContext = context.HttpContext;
var routePrefix = httpContext.GetRouteValue("lang");
context.RedirectUri = $"/{routePrefix.ToString()}/Authentication/LogIn";
return base.RedirectToLogin(context);
}
}
第 2 步: 在 Startup 中修改与重定向到认证页面相关的 cookie 认证声明:
services.AddScoped<CustomCookieAuthenticationEvents>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/Authentication/LogIn");
options.EventsType = typeof(CustomCookieAuthenticationEvents);
});
注意将CustomCookieAuthenticationEvents注册为上面的服务