Search code examples
asp.net-coreasp.net-core-mvcasp.net-core-localization

Localize an ASP.NET Core MVC app


I'm struggling with getting my app to localize strings properly. Feel that I've searched every corner of the web without finding something that works that I expect it to.

I use the RouteDataRequestCultureProvider and first problem I'm trying to solve is to be able to use "short hand version" of the culture, e.g. sv instead of sv-SE and that sv is treated as sv-SE when the culture is created. This doesn't happen automatically.

Second is just getting the app to show a localized string. Here is how I configure the localization

public static IServiceCollection ConfigureLocalization(this IServiceCollection services)
{
    services.AddLocalization(options =>
    {
        options.ResourcesPath = "Resources";
    });
    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[]
            {
            new System.Globalization.CultureInfo("sv-SE"),
            new System.Globalization.CultureInfo("en-US")                        
            };                
        options.DefaultRequestCulture = new RequestCulture(culture: "sv-SE", uiCulture: "sv-SE");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;                
        options.RequestCultureProviders = new[]
        {
            new RouteDataRequestCultureProvider
            {
                Options = options
            }
        };
    });
    return services;
}

And then in Configure I do app.UseRequestLocalizationOptions(); which inject the options previously configured.

In the folder Resources I've created the resources files Resource.resx and Resource.sv.resx.

In my view file I've tried both injecting IStringLocalizer (which fails since no default implementation is registered) and IStringLocalizer<My.Namespace.Resources.Resource> but none of the options works. I've also tried to old fashion way @My.Namespace.Resources.Resource.StringToLocalize

Is it impossible to have a shared resource file? Don't want to resort to Resource\Views\ViewA.resx and Resource\Controllers\AController.resx.

Thanks


Solution

  • So I got this to work. Inside my Resource folder I have my Lang.resx-files with public access modifier.

    I found this and added a class Lang (named to file LangDummy not to conflict with resource files) that belongs to the root namespace of the project.

    Then in my view imports file @inject Microsoft.Extensions.Localization.IStringLocalizer<My.Namespace.Lang> StringLocalizer and use it @StringLocalizer["PropertyInResxFile"]. Ideally I would like to use the generated static properties for type safety and easier refactoring and using nameof everywhere just feels bloated.

    This works for localization via data annotation attributes as well but here I use ResourceType = typeof(My.Namespace.Resources.Lang), i.e. the class for the resx file