参考:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization。
我应该创建一个SharedResources.cs
类,但我应该把它放在哪里,如果它是空的,或者我需要填充一些数据?
资源文件也一样,我应该创建一个SharedResources.da.resx
文件并将所有共享字符串放在那里?
当我使用的IHtmlLocalizer<SharedResources>
时候,我只是写@using
和指向它SharedResources.cs
驻留的名称空间?
我试图把SharedResources.cs
和SharedResources.da.resx
在资源文件夹,并用它来更改网站语言以丹麦,但它不工作。使用专用的资源文件喜欢Index.da.resx
和IViewLocalizer
工作正常,但IHtmlLocalizer<SharedResources>
似乎没有工作。
当我查看链接到页面底部的示例项目时,我没有发现使用SharedResources的地方,如果有人用它的示例更新它,那将是非常好的。
以下是我试图做到的:
Views/Home/Index.cshtml:
@using Funkipedia.Resources
@using Microsoft.AspNetCore.Mvc.Localization
@inject IHtmlLocalizer<Shared> SharedLocalizer
...
<p>@SharedLocalizer["Hei"]</p>
...
在Startup.cs的ConfigureServices顶部:
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
在Startup.cs中的Configure顶部:
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("nb-NO"),
new CultureInfo("sv-SE"),
new CultureInfo("da-DK")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("nb-NO"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
这是我工作的东西(在ASP.NET Core 2.0中):
代码:
// in ProjectRoot\Startup.cs
services.AddLocalization(opts =>
{
opts.ResourcesPath = "Localized";
});
// in ProjectRoot\Area\Whatever\SomeClass.cs
namespace Com.Company.Project.Area.Whatever
{
public class SomeClass
{
public SomeClass(IStringLocalizer<SomeClass> localizer)
{
// ...
}
}
}
所以这里是一步一步发生的事情,只是为了给出一个想法:
SomeClass
全名: Com.Company.Project.Area.Whatever.SomeClass
Com\Company\Project\Area\Whatever\SomeClass.resx
ResourcesPath
内容前缀:Localized\Com\Company\Project\Area\Whatever\SomeClass.resx
这是查找资源文件的实际路径。
因此,总而言之SharedResources.cs
,只要你将其全名复制为ResourcesPath
项目根目录下的文件夹下的路径,就可以将你的空课程放在任何地方。
在这个例子中:
\
--Area
--Whatever
--SomeClass.cs
--Localized
--Com
--Company
--Project
--Area
--Whatever
--SomeClass.resx
--SomeClass.fr.resx
--SomeClass.da.resx