gpt4 book ai didi

c# - 当应用程序启动或导航到主页时在 url 中设置当前文化

转载 作者:太空狗 更新时间:2023-10-29 23:43:02 24 4
gpt4 key购买 nike

我正在开发一个小型 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>并且有效。

最佳答案

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

创建一个类并实现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);

关于c# - 当应用程序启动或导航到主页时在 url 中设置当前文化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54149233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com