我正在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);
}
我仍然看不到我的应用程序更改语言.我到底做错了什么?