ASP.NET Core中外部类库中的本地化 [英] Localization in external class libraries in ASP.NET Core
问题描述
我有两个项目:
- MyWebApp -ASP.NET Core Web API
- MyServices -.NET Core类库,
,其中包含对以上项目的有用服务
- MyWebApp - ASP.NET Core Web API
- MyServices - .NET Core class library, which contains helpful services for project above
如何使用 IStringLocalizer
将本地化添加到 MyServices ? .resx
文件必须放在哪里?
How can I add localization with IStringLocalizer
to MyServices? Where must be .resx
files located?
推荐答案
这就是我的方法解决了。感谢Popa Andrei的回答,将我定向到正确的地方。
This is how I solved it. Thanks to Popa Andrei answer for directing me to the right place.
解决方案->右键单击->添加->新项目...->。净标准->类库->我使用的名称是ResourceLibrary
Solution -> right click -> Add -> New Project ... -> .Net standard -> Class Library -> I used the name ResourceLibrary
ResourceLibrary
|- Resources
|----- SharedResource.resx
|----- SharedResource.he.resx
|- SharedResource.cs
SharedResource.cs代码:
SharedResource.cs code:
using Microsoft.Extensions.Localization;
namespace ResourceLibrary
{
public interface ISharedResource
{
}
public class SharedResource : ISharedResource
{
private readonly IStringLocalizer _localizer;
public SharedResource(IStringLocalizer<SharedResource> localizer)
{
_localizer = localizer;
}
public string this[string index]
{
get
{
return _localizer[index];
}
}
}
}
web应用程序
右键单击webapp项目->添加->参考...->检查资源库
web application
Right click on webapp project -> Add -> Reference ... -> Check Resource Library
在您的Web应用程序startup.cs中:
In your webapp startup.cs:
using ResourceLibrary;
...
public void ConfigureServices(IServiceCollection services) {
...
services.AddLocalization(o => { o.ResourcesPath = "Resources"; });
services.Configure<RequestLocalizationOptions>(options =>
{
CultureInfo[] supportedCultures = new[]
{
new CultureInfo("en"),
new CultureInfo("he")
};
options.DefaultRequestCulture = new RequestCulture("en");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseRequestLocalization(); //before app.UseMvc()
...
}
示例在控制器中使用:
Example use in controller:
using ResourceLibrary;
...
public class ExampleController : Controller
{
private readonly IStringLocalizer<SharedResource> _sharedLocalizer;
public EmailsController(IStringLocalizer<SharedResource> sharedLocalizer)
{
_sharedLocalizer = sharedLocalizer;
}
[HttpGet]
public string Get()
{
return _sharedLocalizer["StringToTranslate"];
}
查看示例:
View example:
@using Microsoft.AspNetCore.Mvc.Localization
@inject IHtmlLocalizer<ResourceLibrary.SharedResource> SharedLocalizer
<p>@SharedLocalizer["StringToTranslate"]</p>
这篇关于ASP.NET Core中外部类库中的本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!