【问题标题】:Set Current culture in url when application starts or navigates to home page应用程序启动或导航到主页时在 url 中设置当前文化
【发布时间】:2019-06-06 12:51:36
【问题描述】:

我正在开发一个小型 Web 应用程序(Razor Pages),并且我已经添加了本地化功能。我现在遇到的问题如下:

当应用程序第一次加载或用户按下主页按钮(<a href="/"</a>)时,浏览器中的url是这样的:

https://localhost/

当我按下链接 (<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> 并且它有效。

【问题讨论】:

  • 你想通过 {currentCulutre} 说什么?
  • http://localhost/en/ 表示英文,例如..

标签: c# asp.net-core razor-pages


【解决方案1】:

我不知道它的解决方案有多好,但你可以这样解决这个问题:

创建一个类并实现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”{for English})。因此,默认文化名称将添加到 url。应用加载时您不会在 url 中看到它,但是当您按 (<a asp-page="/login"></a>) 时,您会看到您被重定向到 https://localhost/en/login

你必须在startup.cs中注册这个规则Configure方法:

var options = new RewriteOptions().Add(new FirstLoadRewriteRule());
app.UseRewriter(options);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多