【发布时间】:2020-09-21 03:10:10
【问题描述】:
我被要求在net.core 解决方案中实现本地化,如下所示:
-
资源文件必须位于单独的项目(如“MyProject.Common”)中,才能在解决方案中的所有其他项目中使用,
-
资源必须按“部分”划分,例如,我们在 Web 项目中有 3 个区域,如下所示:
-
Users, -
Content, -
Administration,
所以我被要求有类似的东西:
- UsersResources.fr-CA.resx,
- UsersResources.en-CA.resx,
- ContentResources.fr-Ca.resx,
- ...
我开始阅读 Localization is AP-NET core 的文档,但我对它的工作原理有点困惑。 似乎我被告知要做的事情是不可能的。
问题是,我可能需要使用业务、视图和控制器中的资源,因此我正在寻找一种方法来实现它,以便团队可以通过调用 ContentResources.MyCustomResource 来使用旧方法。
有没有办法接近它?
我发现有人提到 https://www.nuget.org/packages/ResXResourceReader.NetStandard 的帖子。
但我不知道它是否符合我的需要......
#编辑: 所以,尝试实现 Laz 的共享资源解决方案。
到目前为止,在启动时我有这个:
在ConfigureServices:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddDataAnnotationsLocalization(options => {
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResources));
services.AddLocalization();
services.Configure<RequestLocalizationOptions>(
opts =>
{
/* your configurations*/
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("fr")
};
opts.DefaultRequestCulture = new RequestCulture("fr", "fr");
opts.SupportedCultures = supportedCultures;
opts.SupportedUICultures = supportedCultures;
}
);
在Configure:
app.UseRequestLocalization();
// used to force culture to fr but doen't seem to work
var cultureInfo = new CultureInfo("fr");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
在 MyProject.Common 中,我有这样的结构:
MyProject.Common
-Resources
--SharedResources.cs
---SharedResources.fr.resx
---SharedResources.en.resx
--UsersResources.cs
---UsersResources.fr.resx
---UsersResources.en.resx
假设我想使用SharedResources。
在SharedResources.en.resx我添加了资源:
在SharedResources.fr.resx我添加了资源:
现在在我的UserService,Business 层中,我这样做了:
private readonly IStringLocalizer Localizer;
public UserService(IStringLocalizerFactory factory)
{
var type = typeof(SharedResources);
var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
_localizer = factory.Create(type);
}
public void Test()
{
var test = Localizer["Test"]; //using the key of resources file i want
}
但我在test 变量中得到的结果是“Test”,它是资源的key,而不是value。
【问题讨论】:
-
你可以参考这个讨论类似需求的SO线程:stackoverflow.com/a/52775064/6751634
-
@FeiHan 感谢您的宝贵时间。还尝试了您链接的解决方案,但结果与以下 Laz Ziya 的解决方案相同:我得到的只是资源的
key
标签: asp.net-core localization resources