簡體   English   中英

在應用程序啟動或導航到主頁時在URL中設置當前文化

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM