question

SonalSinghal-2442 avatar image
0 Votes"
SonalSinghal-2442 asked ZhiLv-MSFT commented

How to add custom culture (ex: en-MX;english-Mexico) in .net core?

How can we add custom culture in .net core 3.1. We do have "CultureAndRegionInfoBuilder class exists in .net framework to create and register a new culture, but how can we achieve the same in .net core.
For ex: Mexico default culture is es-MX and we are looking to add a custom culture en-MX ( english-Mexico) .

dotnet-aspnet-core-general
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @SonalSinghal-2442,

You can refer this tutorial to provide localized resources for the languages and cultures you support.

0 Votes 0 ·

Hi @ZhiLv-MSFT ,


I have already gone through the microsoft docs link as provided by you. But it didn't mention anything about adding a custom culture in .net core 3.1.
How can i create a custom culture and register it.


0 Votes 0 ·

I think you're running into this issue: https://github.com/dotnet/msbuild/issues/1454#issuecomment-430315767

Right now, MSBuild does not produce localized satellite resource assemblies for custom cultures, or more specifically, cultures that don't exist in the list returned by CultureInfo.GetCultures. The issue mentions some workarounds but there's also some comments that they might not be particularly usable for all cases.

Please add your voice to the issue as it helps us prioritize work.

0 Votes 0 ·
Show more comments

1 Answer

ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered ZhiLv-MSFT commented

Hi @SonalSinghal-2442,

As we all known, each language and culture combination (other than the default language) requires a unique resource file. You create resource files for different cultures and locales by creating new resource files in which the ISO language codes are part of the file name (for example, en-us, fr-ca, and en-gb). These ISO codes are placed between the file name and the .resx file extension, as in Welcome.es-MX.resx (Spanish/Mexico).

Based on the official sample, to add a custom culture: Spanish/Mexico, you could refer the following steps:

  1. Create a Spanish/Mexico resource page (About2.es-MX.resx) for the About2 view page and add the localize text.

    146047-image.png

  2. Register the location and add the supported Cultures in the Startup.cs file

      public void ConfigureServices(IServiceCollection services)
         {
             services.AddDbContext<ApplicationDbContext>(options =>
             {
                 options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
             });
    
             services.AddIdentity<ApplicationUser, IdentityRole>()
                 .AddEntityFrameworkStores<ApplicationDbContext>()
                 .AddDefaultTokenProviders();
    
             #region snippet1
             services.AddLocalization(options => options.ResourcesPath = "Resources");
    
             services.AddMvc()
                 .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                 .AddDataAnnotationsLocalization();
             #endregion
    
             services.AddTransient<IEmailSender, AuthMessageSender>();
             services.AddTransient<ISmsSender, AuthMessageSender>();
    
             services.Configure<RequestLocalizationOptions>(options =>
             {
                 var supportedCultures = new [] { "en-US", "fr", "es-MX" };
                 options.SetDefaultCulture(supportedCultures[0])
                     .AddSupportedCultures(supportedCultures)
                     .AddSupportedUICultures(supportedCultures);
             });
         }
    
         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
         {
             if (env.IsDevelopment())
             {
                 app.UseDeveloperExceptionPage();
                 app.UseDatabaseErrorPage();
             }
             else
             {
                 app.UseExceptionHandler("/Home/Error");
    
                 // For more information on applying migrations at runtime, see:
                 // https://docs.microsoft.com/ef/core/managing-schemas/migrations/applying#apply-migrations-at-runtime
                 try
                 {
                     using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                         .CreateScope())
                     {
                         serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                             .Database.Migrate();
                     }
                 }
                 catch { }
             }
    
             app.UseHttpsRedirection();
             app.UseStaticFiles();
             app.UseRouting();
    
             #region snippet2
             var supportedCultures = new[] { "en-US", "fr", "es-MX" };
             var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
                 .AddSupportedCultures(supportedCultures)
                 .AddSupportedUICultures(supportedCultures);
    
             app.UseRequestLocalization(localizationOptions);
             #endregion
    
             app.UseAuthentication();
             app.UseAuthorization();
    
             app.UseEndpoints(endpoints =>
             {
                 endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
             });
         }
    

  3. The About2 View page as below:

       @using Microsoft.AspNetCore.Mvc.Localization
            
         @inject IViewLocalizer Localizer
            
         @{
             ViewData["Title"] = Localizer["About2"];
         }
         <h2>@ViewData["Title"].</h2>
         <h3>@ViewData["Message"]</h3>
            
         <p>@Localizer["Use this area to provide additional information."]</p>
    

    The About2 action method:

       public IActionResult About2()
         {
             ViewData["Message"] = _localizer["Your application description page."];
    
             return View();
         }
    

    The result like this: since the above resource page only applies to the View page, in the controller, the Message is not localized.

    146096-1.gif

    [Note]For the language select element, you could check the _SelectLanguagePartial.cshtml(in the Views/Shared folder).


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Best regards,
Dillion


image.png (88.9 KiB)
1.gif (233.4 KiB)
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi Dillion,

We were able to add Spanish/Mexico(es-MX) culture in our .net core3.1 app the same way you provided above and it's working fine. Problem we are facing is adding English/Mexico (en-MX) custom culture.

I have added a resource file About.en-MX.resx in the resources folder and added "en-MX" in the supported cultures list in startup class. But when i am running the application and selecting "Mexico - English" culture from the dropdown. It's picking resource keys from About.en.resx file, not from "en-MX" file. As per the requirement we have different content available in both "About.en.resx" and "About.en-MX.resx" file. So, we want right file to be picked up on culture change.

Please advise..

0 Votes 0 ·

Hi @SonalSinghal-2442,

The English/Mexico (`en-MX`) custom culture is not a valid culture. If you search the language code or refer this article, you can find that the dialect of Spanish spoken in Mexico is "es-MX", instead of en-MX, and if we continue to configure it as the en-MX, it will show unknown language when you select the language, and the Location will not work.

0 Votes 0 ·

Hi Dillion,

That's right. en-MX is not a valid culture and but, there is a requirement in my project where we are looking to add custom culture.
I found this article( https://stackoverflow.com/questions/1304507/create-custom-culture-in-asp-net ) on stack overflow and looking to implement something like this in .net core.
Let me know your thoughts.


0 Votes 0 ·
Show more comments