当应用程序启动或导航到主页时,在URL中设置当前区域性

时间:2019-01-11 15:13:29

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

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

当应用程序首次加载或用户按下主屏幕按钮(<a href="/"</a>)时,浏览器中的网址是:

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>,它可以正常工作。

1 个答案:

答案 0 :(得分: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”(英语))。因此,默认的区域性名称将添加到url中。加载应用程序时,您不会在url中看到它,但是当您按(<a asp-page="/login"></a>)时,您会看到您已重定向到https://localhost/en/login

您必须使用startup.cs方法在Configure中注册此规则:

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