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

Anonymous
2021-11-01T16:44:45.723+00:00

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) .

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,158 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2021-11-03T09:28:12.28+00:00

    Hi @Anonymous ,

    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://learn.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?}");  
          });  
      }  
      
      1. 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


  2. Ørjan Olsen 21 Reputation points
    2023-01-03T15:45:58.103+00:00

    Depending on what you want to achieve down the line, you may be able to achieve this by rewriting the accept-language request header early in the middleware pipeline. This is assuming your client sends the en-MX value and that you don't want custom localization for this case.

    app.Use((context, next) =>  
    {  
    	if (context.Request.Headers.AcceptLanguage.First().ToLower() == "en-mx")  
    	{  
    		context.Request.Headers.AcceptLanguage = new StringValues("en");  
    	}  
    	return next(context);  
    });  
    
    0 comments No comments