问题描述
我想通过.NET Core 3.1的RESX文件中的值获取转换后的字符串的名称。
System.Resources.ResourceManager rm =
new System.Resources.ResourceManager("Resources.Views.Shared._Layout.de.resx",this.GetType().Assembly);
return await Task.Run(() => rm.GetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture,true,true)
.OfType<DictionaryEntry>()
.FirstOrDefault(e => e.Value.ToString() == value).Key.ToString());
我的资源文件如下所示。
错误消息如下。
解决方法
如果您查看the documentation,将看到ASP.NET Core引入了IStringLocalizer和IStringLocalizer。
在幕后,IStringLocalizer使用ResourceManager和ResourceReader。文档中的基本用法:
public class StringLocalizerController : Controller
{
private readonly IStringLocalizer localizer;
public StringLocalizerController(IStringLocalizerFactory factory)
{
var assemblyName = new AssemblyName(this.GetType().Assembly.FullName);
localizer = factory.Create("SharedResource",assemblyName.Name);
}
public IActionResult SharedResource()
{
return Content(localizer["AAA"]);
}
}
启动:
services.AddLocalization(options => options.ResourcesPath = "Resources/View/Shared");