我正在try 本地化我的ASP.NET Core 8 MVC应用程序.我已经遵循了所有步骤,但我无法将我的共享视图本地化.

以下是我的Program.cs条:

using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Localization;
using System.Globalization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddLocalization(opt => opt.ResourcesPath = "Localization");
builder.Services.AddControllersWithViews()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();

string[] supportedLanguages = ["en", "jp"];
IList<CultureInfo> cultures = new List<CultureInfo>();
foreach(string lang in supportedLanguages)
{
    cultures.Add(new CultureInfo(lang));
}

builder.Services.Configure<RequestLocalizationOptions>(opt =>{
    opt.DefaultRequestCulture = new RequestCulture(supportedLanguages[0]);
    opt.SupportedCultures = cultures;
});

var app = builder.Build();
app.UseRequestLocalization();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Views/ViewImports.cshtml:

@using newApp
@using newApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

我将我的资源文件放在Localization文件夹中, struct 如下:

Localization > Views > Shared > _Layout.en.resx
Localization > Views > Shared > _Layout.jp.resx

我使用以下代码来调用本地化@Localizer["search"]-以下是我在HomeController中的操作:

public IActionResult Lang(string? culture)
{
    if (culture != null)
    {
        Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName, 
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), 
            new CookieOptions{ Expires = DateTime.Now.AddYears(1) }
        );
    }

    string referer = Request.Headers["Referer"].ToString();

    if (string.IsNullOrEmpty(referer))
        referer = "/";

    return Redirect(referer);
}

我仍然看不到我的应用程序更改语言.我到底做错了什么?

推荐答案

首先,文化jp不能被识别,ja是正确的.

其次,需要SupportedUICultures个.

Program.cs

using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
using System.Globalization;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddLocalization(opt => opt.ResourcesPath = "Localization");
builder.Services.AddControllersWithViews()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();

string[] supportedLanguages = ["en", "ja"];    //1.ja represents japanese
IList<CultureInfo> cultures = new List<CultureInfo>();
foreach (string lang in supportedLanguages)
{
    cultures.Add(new CultureInfo(lang));
}

builder.Services.Configure<RequestLocalizationOptions>(opt => {
    opt.DefaultRequestCulture = new RequestCulture(supportedLanguages[0]);
    opt.SupportedCultures = cultures;
    opt.SupportedUICultures = cultures;    //2.supportedui needed
});

var app = builder.Build();
app.UseRequestLocalization();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

enter image description here

Csharp相关问答推荐

在依赖性注入和继承之间进行 Select

将列表字符串映射为逗号分隔字符串<>

SignalR客户端不会打印队列位置'

`Task`只有在C#中等待时才会运行吗?

如果存在对CodeAnalysis.CSharp的引用,则不能引用netStandard2.0库

如果属性名为xyz,我需要使用System.Text.Json修改字符串类型的值""<>

ITypeLib2.GetLibStatistics()在C#中总是抛出AccessViolationException

Blazor-从数据库内部服务器提取错误

为什么SignalR在每个Blazor服务器应用程序启动时最多启动8个服务器?

XUNIT是否使用测试数据的源生成器?

Rx.Net窗口内部可观测数据提前完成

如何使用自定义负载均衡器管理Ocelot负载均衡器中的多线程和批读取

在C#中过滤Excel文件

是否可以将Collectionview中的数组与ObservableCollection绑定?

升级后发出SWITCH语句

Blazor服务器项目中的Blazor/.NET 8/Web API不工作

如何从SignalR获取连接客户端的域

在.Net 8 Visual Studio 2022中启用本机AOT发布时发布失败

在Visual Studio 2022中查找Xamarin模板时遇到问题

SqlException:无法打开数据库.升级到Dotnet 8后-数据库兼容性版本-非EFCore兼容性级别