问题
I don't have much experience working with resource files, but the little that I have is from Web Forms. There from what I can tell is you create a resource file called let's say InternalMessages.resx and then you create a Spanish version Errors.es.resx. Now if I have set up my code correctly for choosing language, all I have to do it call InternalMessages.MyMessage and it will choose the right language, regardless of what page you are on.
In core, this concept doesn't seem to work. no matter which language I switch to, it just uses the English translations. From reading the documentation, it appears that core wants me to create resource files on the page level, however, I find this very bad practice because it doesn't follow the DRY principle. Sometimes we have values that are used on more than one page and if we decide to change verbiage of that value, we have to go and find it everywhere in the system, other times you may miss that you already have a translation for that or something very similar that would do and you end up paying for translation all over again.
I want to segregate my resources into categories and use them like that. So having the InternalMessages.resx file is how I want to go, however, that doesn't seem to work for me. Here is a SO answer I followed to setup my localization. Localization in Asp.Net Core
So I have a working drop-down with languages, but the code just always pulls the values from InternalMessages.resx versus InternalMessages.es.resx when I switch to Spanish. Why is that?
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Test = InternalMessages.Test;
return View();
}
}
In the view I have:
<p>@ViewBag.Test</p>
I have also tried doing this:
public class HomeController : Controller
{
private readonly IStringLocalizer<InternalMessages> _localizer;
public HomeController(IStringLocalizer<InternalMessages> localizer)
{
_localizer = localizer;
}
public IActionResult Index()
{
ViewBag.Test = _localizer["Test"];
return View();
}
}
But in this case the value I always get is Test
I also tried injecting directly in the View but the result is same as above, just a word Test
@inject IHtmlLocalizer<InternalMessages> SharedLocalizer
<p>@SharedLocalizer["Test"]</p>
来源:https://stackoverflow.com/questions/46990941/localization-files-in-asp-net-core