当应用程序启动或导航到主页时,在 url 中设置当前文化
Set Current culture in url when application starts or navigates to home page
我正在开发一个小型 Web 应用程序 (Razor Pages),我已将本地化添加到其中。我现在遇到的问题如下:
当应用程序第一次加载或当用户按下主页按钮 (<a href="/"</a>)
时,浏览器中的 url 是这样的:
https://localhost/
当我按下 link (<a asp-page="/login"></a>)
时,它会将我导航到 https://localhost/login
而不是 https://localhost/{currentCulture}/login
因此,我希望它是这样的:
https://localhost/{currentCulture}/
例如,对于英语 --> https://localhost/en/
我已经设置了默认的当前文化,它在应用程序启动时应用,但它没有写在 url。
我已按照本教程将本地化添加到我的应用程序中:http://www.ziyad.info/en/articles/10-Developing_Multicultural_Web_Application
更新:
当用户按下主页按钮时,我这样做了:<a href="/@CultureInfo.CurrentCulture.Name"></a>
它起作用了。
我不知道这个解决方案有多好,但是你可以这样解决这个问题:
创建 class 并实施 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 == "/"
仅在应用首次加载时为真(当您按主页时,request.path 为“/en”{英语})。因此,默认区域性名称将添加到 url。当应用程序加载时,您不会在 url 中看到它,但是当您按 (<a asp-page="/login"></a>)
时,您会看到您被重定向到 https://localhost/en/login
.
您必须在 startup.cs
的 Configure
方法中注册此规则:
var options = new RewriteOptions().Add(new FirstLoadRewriteRule());
app.UseRewriter(options);
我正在开发一个小型 Web 应用程序 (Razor Pages),我已将本地化添加到其中。我现在遇到的问题如下:
当应用程序第一次加载或当用户按下主页按钮 (<a href="/"</a>)
时,浏览器中的 url 是这样的:
https://localhost/
当我按下 link (<a asp-page="/login"></a>)
时,它会将我导航到 https://localhost/login
而不是 https://localhost/{currentCulture}/login
因此,我希望它是这样的:
https://localhost/{currentCulture}/
例如,对于英语 --> https://localhost/en/
我已经设置了默认的当前文化,它在应用程序启动时应用,但它没有写在 url。
我已按照本教程将本地化添加到我的应用程序中:http://www.ziyad.info/en/articles/10-Developing_Multicultural_Web_Application
更新:
当用户按下主页按钮时,我这样做了:<a href="/@CultureInfo.CurrentCulture.Name"></a>
它起作用了。
我不知道这个解决方案有多好,但是你可以这样解决这个问题:
创建 class 并实施 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 == "/"
仅在应用首次加载时为真(当您按主页时,request.path 为“/en”{英语})。因此,默认区域性名称将添加到 url。当应用程序加载时,您不会在 url 中看到它,但是当您按 (<a asp-page="/login"></a>)
时,您会看到您被重定向到 https://localhost/en/login
.
您必须在 startup.cs
的 Configure
方法中注册此规则:
var options = new RewriteOptions().Add(new FirstLoadRewriteRule());
app.UseRewriter(options);