Guillaume Lujan
Guillaume Lujan

Reputation: 79

ASP.NET Core 1.0 Application resources naming

I am trying to get localization for my MVC views in ASP.NET Core 1.0 web application.

So far i've set up my Startup.cs file with ConfigureServices method :

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRouting(configureOptions => configureOptions.LowercaseUrls = true);
        services.AddMvc()
            .AddViewLocalization(setupAction => setupAction.ResourcesPath = "Resources")
            .AddDataAnnotationsLocalization();
    }

Then my Configure method :

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        loggerFactory.MinimumLevel = LogLevel.Information;
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        CultureInfo defaultCulture = new CultureInfo("en");
        List<CultureInfo> supportedCultures = new List<CultureInfo>
        {
            defaultCulture,
            new CultureInfo("fr")
        };

        RequestLocalizationOptions requestLocalizationOptions = new RequestLocalizationOptions
        {
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures,
        };

        RequestCulture defaultRequestCulture = new RequestCulture(defaultCulture);
        //Insert this at the beginning of the list since providers are evaluated in order until one returns a not null result
        requestLocalizationOptions.RequestCultureProviders.Insert(0, new UrlCultureProvider());
        app.UseRequestLocalization(requestLocalizationOptions, defaultRequestCulture);

        app.UseIISPlatformHandler();
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "defaultWithCulture",
                template: "{culture}/{controller}/{action}/{id?}",
                defaults: new { culture = "en", controller = "Home", action = "Index" },
                constraints: new { culture = "en|fr" });
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}/{id?}",
                defaults: new { culture = "en", controller = "Home", action = "Index" });
        });
        app.UseStatusCodePages();
    }

And finally my UrlCultureProvider class that helps me to set the culture when it is provided in the url :

public class UrlCultureProvider : IRequestCultureProvider
{
    public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {

        var url = httpContext.Request.Path;

        //Quick and dirty parsing of language from url path, which looks like "/api/de-DE/home"
        //This wont be needed in RC2 since an extension method GetRouteData has been added to HttpContext
        //which means we could just get the the "language" parameter from the route data
        var parts = httpContext.Request.Path.Value.Split('/');
        if (parts.Length < 2)
        {
            return Task.FromResult<ProviderCultureResult>(null);
        }
        var hasCulture = Regex.IsMatch(parts[1], @"^[a-z]{2}$");

        if (!hasCulture)
        {
            return Task.FromResult<ProviderCultureResult>(null);
        }

        var culture = parts[1];
        return Task.FromResult(new ProviderCultureResult(culture));
    }
}

The culture is set to fr or en if its presents in the url. Than i have two resources files on my 'Resources' folder :

Views.Home.Index.cshtml.resx

Views.Home.Index.cshtml.fr.resx

And in my _ViewImports.cshtml file, i have this code :

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

Finally, i have in my Index view a resource call :

@Localization["Test"]

I got this working with "en" culture but not "fr" culture.

Do you know what is going on there ?

Thank you.

Upvotes: 1

Views: 616

Answers (3)

Iren Saltalı
Iren Saltalı

Reputation: 536

As I see there is little in naming errors your project.

First of all you should not use .cshtml extension they should be like:

Views.Home.Index.en.resx
Views.Home.Index.fr.resx

If you like to use localization for _ViewImports.cshtml their name should be

Views.Shared._ViewImports.en.resx
Views.Shared._ViewImports.fr.resx

I thought most probably _ViewImports.cshtml in 'Shared' folder and I used 'Shared' for naming.

And finally if you have to inject IViewLocalizer for every .cshtml separately.

You can read detailed documentation by Microsoft.

Upvotes: 0

sebjones
sebjones

Reputation: 11

I'm sure this is old by now but just in case it helps someone, I think the problem might be that you don't need to include .cshtml in the resx file name. This might explain why it's only finding the default text.

When you use @Localizer["Some text"] it will look for the key "Some text" in the relevant resource file, but if it can't be found (or the resx file can't be found), it will use the key as the default text.

Cheers

Upvotes: 1

Guillaume Lujan
Guillaume Lujan

Reputation: 79

After some investigation, it looks like Visual Studio has currently a bug that disallow resources files (.Resx) to be discovered when debugging on the IDE. the issue is addressed here :

https://github.com/aspnet/Mvc/issues/3846

Hope this bug will be fixed in ASP.NET Core 1.0 RC2.

Anyway, when i deploy to azure, resources files are correctly found.

Upvotes: 0

Related Questions