[英]Set Current culture in url when application starts or navigates to home page
我正在开发一个小型Web应用程序(Razor Pages),我已经添加了本地化。 我现在遇到的问题如下:
当应用程序第一次加载或用户按下主页按钮(<a href="/"</a>)
,浏览器中的URL为:
https://localhost/
当我按下一个链接(<a asp-page="/login"></a>)
它会导航我到https://localhost/login
而不是https://localhost/{currentCulture}/login
因此,我希望它是这样的:
https://localhost/{currentCulture}/
例如,对于english - > https://localhost/en/
我已经设置了默认的当前文化,它在应用程序启动时应用,但不会在URL中写入。
我已按照本教程向我的应用添加本地化: http : //www.ziyad.info/en/articles/10-Developing_Multicultural_Web_Application
更新:
当用户按下主页按钮时,我这样做: <a href="/@CultureInfo.CurrentCulture.Name"></a>
并且它可以正常工作。
我不知道它是多么好的解决方案,但你可以解决这个问题:
创建一个类并实现Microsoft.AspNetCore.Rewrite.IRule
:
public class FirstLoadRewriteRule : IRule
{
public void ApplyRule(RewriteContext context)
{
var culture = CultureInfo.CurrentCulture;
var request = context.HttpContext.Request;
if(request.Path == "/")
{
request.Path = new Microsoft.AspNetCore.Http.PathString($"/{culture.Name}");
}
}
}
在您的应用程序request.Path == "/"
仅在应用程序第一次加载时才会为true(当您按下home,request.path为“/ en”{for English})。 因此,默认文化名称将添加到URL。 在加载应用时,您不会在网址中看到它,但是当您按(<a asp-page="/login"></a>)
,您将看到您被重定向到https://localhost/en/login
。
您必须在Configure
方法中的startup.cs
中注册此规则:
var options = new RewriteOptions().Add(new FirstLoadRewriteRule());
app.UseRewriter(options);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.