ASP .NET Core 2 Localization get all string for ne

2019-02-25 17:23发布

问题:

There are a ASP .NET Core application with localization as https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization.

The all string are localized with default language with a IStringLocalizer _localizer["About Title"] - no a .resx file.

Now I want add a new language.

Can I generate all resource files a automatically?

Example I have

private readonly IStringLocalizer<SharedResource> _localizerG;
private readonly IStringLocalizer<HomeController> _localizerC;

_localizerG["Your contact page. (G)"]
_localizerC["Your contact page. (C)"]

Can I generate (and update in future) a .resx files for new a language uk-UA with filled strings

  1. SharedResource.uk-UA.resx
    • Name: Your contact page. (G)
    • Value: Your contact page. (G)
  2. HomeController.uk-UA.resx
    • Name: Your contact page. (C)
    • Value: Your contact page. (C)

回答1:

As an option you can log those strings by creating a custom localizer. Then you can create required resources for those strings.

For example, create a localizer like this:

using Microsoft.Extensions.Localization;
public class MyStringLocalizer<T> : StringLocalizer<T>
{
    public MyStringLocalizer(IStringLocalizerFactory factory) : base(factory)
    {
    }

    public override LocalizedString this[string name]
    {
        get
        {
            //Log typeof(T) and name
            return base[name];
        }
    }

    public override LocalizedString this[string name, params object[] arguments]
    {
        get
        {
            //Log typeof(T) and name
            return base[name, arguments];
        }
    }
}

Then in ConfigureServices method, register the localizer:

services.AddTransient(typeof(IStringLocalizer<>), typeof(MyStringLocalizer<>));