我的剃刀页面看起来像这样。
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
<h1>@Localizer["Index"]</h1>
...
我的Startup.cs包含以下内容。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddLocalization(a => a.ResourcesPath = "/");
services.Configure<RequestLocalizationOptions>(a =>
{
CultureInfo[] supportedCultures = {
new CultureInfo("sv-SE"),
new CultureInfo("se")
};
a.DefaultRequestCulture = new RequestCulture("se");
a.SupportedCultures = supportedCultures;
a.SupportedUICultures = supportedCultures;
});
...
}
我将一个名为Controllers.HomeController.se.resx的文件直接放在项目的根目录中。控制器HomeController包含注入。
public class HomeController : Controller
{
private readonly Context _context;
private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(Context context, IStringLocalizer<HomeController> localizer)
{
_context = context;
_localizer = localizer;
}
...
}
应用程序不会崩溃,但重新连接的字符串是Index而不是RESX文件中的值。我试图尽可能地跟随the docs,但显然我错过了一些东西。我需要帮助找到那将是什么。
我在构造函数中打破并检查了_localizer [“Index”]的值。正如所料,未找到文件的标志设置为true。检查SearchedLocation的值给了我Web ... Controllers.MemberController。我无法判断这三个点是否是项目根目录中RESX文件的正确点。我也期待名字的某个地方。
如果要将资源文件放在项目的根目录中,则应将ResourcesPath
设置如下
services.AddLocalization(a => a.ResourcesPath = ""); //empty string
有了这个设置,SearchedLocation
会给你Web.Controllers.MemberController
,它指向项目根目录中的Controllers.MemberController.resx
文件。
要在视图中使用本地化,您必须遵循Views.{ControllerName}.{ViewName}.resx
模式。例如,如果你有HomeController
和About
视图,你需要有Views.Home.About.resx
文件来使用本地化。
搜索本地化文件时,另一个常规资源阅读器会跟踪相应文件夹中的文件而不是点分隔名称。例如,如果ResourcesPath
设置为"Resources"
,则以下变体是相同的
Resources.Views.Home.About.resx
Resources\Views.Home.About.resx
Resources\Views\Home.About.resx
Resources\Views\Home\About.resx
因此,可以按文件夹构建本地化文件。
你没有指定你在app.UseRequestLocalization()
中添加了Startup.cs
。如果您不这样做,您的应用程序将无法确定请求文化,它将始终指向默认资源文件。阅读更多in the docs。
注意
有两种方法可以通过RequestLocalizationOptions
将services.Configure<RequestLocalizationOptions>
配置为请求本地化,或者将构造的选项对象(或委托)传递给app.UseRequestLocalization
。实际上,这些方法之间没有区别,它们在本地化中间件方面完全相同。但是,如果在应用程序的任何时候你需要获得RequestLocalizationOptions
,你将无法将值传递给app.UseRequestLocalization
。但它很容易与services.Configure<RequestLocalizationOptions>
(它的一般方法描述in the docs)一起使用
public class HomeController : Controller
{
private readonly RequestLocalizationOptions _requestLocalizationOptions;
public HomeController(IOptions<RequestLocalizationOptions> options)
{
_requestLocalizationOptions = options.Value;
}
//..
}