Globalization and localization concepts

In this section, you will learn about the concepts of globalization and localization and how they will allow you to further optimize your websites for internationalization.

For additional information on globalization and localization, please visit https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization.

So, how do you get started? Well, first of all, let's look at how to make the Tic-Tac-Toe application localizable by using the String Localizer:

  1. Go to the Services folder and add a new service called CultureProviderResolverService. This will retrieve the culture set by looking at the Culture query string, the Culture cookie, and the Culture session variable (created in the previous section of this chapter). 
  2. Implement CultureProviderResolverService by inheriting it from RequestCultureProvider and overriding its specific methods:
        public class CultureProviderResolverService :  
RequestCultureProvider { private static readonly char[] _cookieSeparator =
new[] {'|' }; private static readonly string _culturePrefix = "c="; private static readonly string _uiCulturePrefix = "uic="; //... }
  1. Add the DetermineProviderCultureResult method to the CultureProviderResolverService class: 
public override async Task<ProviderCultureResult> 
DetermineProviderCultureResult(HttpContext httpContext) { if (GetCultureFromQueryString(httpContext,
out string culture)) return new ProviderCultureResult(culture, culture); else if (GetCultureFromCookie(httpContext, out culture)) return new ProviderCultureResult(culture, culture); else if (GetCultureFromSession(httpContext, out
culture)) return new ProviderCultureResult(culture, culture); return await NullProviderCultureResult; }
  1. Add the following method, which will allow us to get Culture from a query string:
private bool GetCultureFromQueryString(   HttpContext httpContext, out string culture) 
          { 
            if (httpContext == null) 
            { 
              throw new ArgumentNullException(nameof(httpContext)); 
            } 
 
            var request = httpContext.Request; 
            if (!request.QueryString.HasValue) 
            { 
              culture = null; 
              return false; 
            } 
 
            culture = request.Query["culture"]; 
            return true; 
          } 
  1. Add the following method, which will allow us to get Culture from cookies: 
private bool GetCultureFromCookie(HttpContext httpContext, out 
string culture) { if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } var cookie = httpContext.Request.Cookies["culture"]; if (string.IsNullOrEmpty(cookie)) { culture = null; return false; } culture = ParseCookieValue(cookie); return !string.IsNullOrEmpty(culture); }
  1. Here's the method that we will use to parse a cookie value: 
public static string ParseCookieValue(string value) 
{ 
  if (string.IsNullOrWhiteSpace(value))   return null;             
  var parts = value.Split(_cookieSeparator, 
StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) return null; var potentialCultureName = parts[0]; var potentialUICultureName = parts[1]; if (!potentialCultureName.StartsWith(_culturePrefix) ||
!potentialUICultureName.StartsWith(_uiCulturePrefix)) return null; var cultureName = potentialCultureName.
Substring(_culturePrefix.Length); var uiCultureName = potentialUICultureName.Substring
(_uiCulturePrefix.Length); if (cultureName == null && uiCultureName == null) return null; if (cultureName != null && uiCultureName == null) uiCultureName =
cultureName; if (cultureName == null && uiCultureName != null) cultureName = uiCultureName; return cultureName; }
  1. Now, add the following method, which allows us to get Culture from the session: 
private bool GetCultureFromSession(HttpContext httpContext,
out string culture) { culture = httpContext.Session.GetString("culture"); return !string.IsNullOrEmpty(culture); }
  1. Add the localization service at the top of the ConfigureServices method in the Startup class:
        public void ConfigureServices(IServiceCollection services) 
        { 
          services.AddLocalization(options => options.
ResourcesPath = "Localization"); //... }

  1. Add the localization middleware to the Configure method in the Startup class and define the supported cultures.

Note that the order of adding middleware is important, as you have already seen. You have to add the localization middleware just before the MVC middleware:

        ... 
        var supportedCultures =
CultureInfo.GetCultures(CultureTypes.AllCultures); var localizationOptions = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }; localizationOptions.RequestCultureProviders.Clear(); localizationOptions.RequestCultureProviders.Add(new
CultureProviderResolverService()); app.UseRequestLocalization(localizationOptions); app.UseMvc(...);

Note that you can use different methods to change the culture of your applications:

  • Query strings: Provide the culture in the URI
  • Cookies: Store the culture in a cookie
  • Browser: Browser page language settings
  • Custom: Implement your own provider (shown in this example)
  1. In the Solution Explorer, add a new folder called Localization (it will be used to store the resource files) and create a subfolder called Controllers. Then, within this folder, add a new resource file called GameInvitationController.resx:
Note that you can put your resource files either into subfolders (for example, Controllers, Views, and so on) or directly name your files accordingly (for example, Controllers.GameInvitationController.resx, Views.Home.Index.resx, and so on). However, we advise that you use the folder approach for clarity, readability, and better organization of your files.
If you see errors while using your resource files with .NET Core, right-click on each file and select Properties. Then, check each file to ensure that the Build Action is set to Content instead of Embedded Resource. These are bugs that should have been fixed by the final release, but if they haven't you can use this handy workaround to make everything work as expected.
  1.  Open the GameInvitationController.resx resource file and add a new GameInvitationConfirmationMessage in English:

  1. In the same Controllers folder, add a new resource file for the French translations called GameInvitationController.fr.resx:

  1. Go to GameInvitationController, add stringLocalizer, and update the constructor implementation:
        private IStringLocalizer<GameInvitationController>
_stringLocalizer; private IUserService _userService; public GameInvitationController(IUserService userService,
IStringLocalizer<GameInvitationController> stringLocalizer) { _userService = userService; _stringLocalizer = stringLocalizer; }
  1. Add a new Index method to GameInvitationController. This will return a localized message, depending on the application locale settings:
        [HttpPost] 
        public IActionResult Index(
GameInvitationModel gameInvitationModel) { return Content(_stringLocalizer[
"GameInvitationConfirmationMessage",
gameInvitationModel.EmailTo]); }
  1. Start the application in English (the default culture) and register a new user until you get the following text message, which should be in English:

  1. Change the application language to French by using the User Interface Language Drop-Down. Then, register a new user until you get the following text message, which should now be in French, as shown in the following screenshot:

In this section, you have learned how to localize any type of string within your applications, which can be useful for some of your specific application use cases. However, this is not the recommended approach when working with views.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.176.80