c# - 多语言 Asp.Net Core 3.1 MVC 应用程序不在 url 中显示语言代码

标签 c# asp.net-mvc asp.net-core

我正在开发一个包含多语言内容的 ASP.NET CORE 应用程序。文化正在成功改变,也可以在应用程序 cookie 中查看。

enter image description here

但 URL 不会因语言切换而改变。 我在启动时尝试过如下:

启动配置服务:

services.AddLocalization(options => options.ResourcesPath = "Resources");

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
        options => { options.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization(options =>
    {
        options.DataAnnotationLocalizerProvider = (type, factory) =>
            factory.Create(typeof(ShareResource));
    });

启动配置:

var supportedCultures = new List<CultureInfo>()
{
    new CultureInfo("en"),
    new CultureInfo("de"),
    new CultureInfo("fr"),
    new CultureInfo("pt"),
    new CultureInfo("tr")
};

var options = new RequestLocalizationOptions()
{
    DefaultRequestCulture = new RequestCulture("en"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures,
    RequestCultureProviders = new List<IRequestCultureProvider>()
    {
        new QueryStringRequestCultureProvider(),
        new CookieRequestCultureProvider()
    }
};
app.UseRequestLocalization(options);

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "defaultWithLang",
        pattern: "{lang}/{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

HomeController 中:

public IActionResult ChangeLang(string lang)
{
    Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(lang)),
        new CookieOptions(){
            Expires = DateTimeOffset.UtcNow.AddYears(1)
        });

    return Redirect(Request.Headers["Referer"].ToString());
}

我希望显示的 URL 类似于“http://domain/en/controller/action”,但它不会因切换语言而改变,并且总是像没有语言的“http://domain/controller/action”代码。

在启动时或其他地方,我还需要在我的代码中添加什么吗? 感谢您的帮助。

最佳答案

当您手动设置 url 时会发生什么?

现在,您正在使用默认回退路由。

检查这个:

    routes.MapRoute(
        name: "LocalizedDefault",
        template: "{lang:lang}/{controller=Home}/{action=Index}/{id?}"
    );

    routes.MapRoute(
        name: "default",
        template: "{*catchall}",
        defaults: new { controller = "Home", action = "RedirectToDefaultLanguage", lang = "en" });

你还可以添加lang约束

services.Configure<RouteOptions>(options =>
{
    options.ConstraintMap.Add("lang", typeof(LanguageRouteConstraint));
});

然后在路由配置上面添加以下几行

var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);

关于c# - 多语言 Asp.Net Core 3.1 MVC 应用程序不在 url 中显示语言代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63916061/

相关文章:

c# - Xamarin 表格 : How to access button name in XAML from C#?

c# - 在 C# 中为 WP7 选择一个随机字符串

asp.net-mvc - 在 asp.net mvc4 smtp.Send(mail) 中发送邮件失败

c# - 将图像添加到数据库

asp.net-core - 防止 ASP.NET Core 在单独的程序集中发现 Controller

sql-server - SQL Server与Docker和Entity Framework的连接

c# - 单声道不能消费触摸事件

c# - Owin 声明 - 添加多个 ClaimTypes.Role

c# - 从 1.0.0-rc1-final 中的 appsettings.json 中读取一个值

c# - 在 C# 中优化列表性能