Understanding Resource files in MVC6 RC1

时间:2016-04-21 21:51:04

标签: localization asp.net-core asp.net-core-mvc resx asp.net-core-localization

I've been trying to wrap my head around on how best to implement resource files for multiple languages in MVC6 but due to the changes with every release has me a bit confused on how to actually implement them properly. What is required and what are the constraints?

A few articles I've looked at:

https://damienbod.com/2015/10/21/asp-net-5-mvc-6-localization/

MVC 6 : how to use RESX files?

http://pratikvasani.github.io/archive/2015/12/25/MVC-6-localization-how-to/

I'm trying to set up resource files so that I have English and German available to my users, which would either be based on browser settings or a personal setting within their account.

What would be the best way of achieving this?

Thanks in advance!

Edit:

So as per the article, I've added the following code to Startup.cs:

        services.AddLocalization(options =>
                options.ResourcesPath = "Resources");
        services.AddMvc()
                .AddViewLocalization(Microsoft.AspNet.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization();

        var supportedCultures = new[]
        {
            new CultureInfo("de-DE"),
            new CultureInfo("en-US")
        };

        //Set Default Localization Culture
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        }, new RequestCulture(new CultureInfo("en-US")));

Then within the Resources folder I created new resx files with file names:

  • "Views.Shared._LocalizationTest.en-US.resx"

  • "Views.Shared._LocalizationTest.de-DE.resx"

And my partial view looks like:

@using Microsoft.AspNet.Localization
@using Microsoft.AspNet.Mvc.Localization
@inject IViewLocalizer Localizer

<div>
     @Localizer["TestString"]
</div>

I still seem to be missing something as I am getting "TestString" to show instead of "Test String" for English or "German: Test String" (as per my resource files).

Any ideas?

1 个答案:

答案 0 :(得分:2)

The ASP.NET core default approach is to NOT have your default language strings in a resource file, but just have them wrapped in code. So you could write the app using English strings wrapped in the localizer, and have one German resource file. See my article https://docs.microsoft.com/aspnet/core/fundamentals/localization