ASP.NET Localization of core webapi (single resource file)

Time:2020-8-1

At startupConfigureServicesServices required for registration localizationAddLocalizationandConfigure<RequestLocalizationOptions>


 public void ConfigureServices(IServiceCollection services)
  {
   services.AddLocalization();
   services.Configure<RequestLocalizationOptions>(options =>
   {
    var supportedCultures = new List<CultureInfo>
    {
     new CultureInfo("en-us"),
     new CultureInfo("zh-cn")
    };

    options.DefaultRequestCulture = new RequestCulture(culture: "en-us", uiCulture: "en-us");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
    options.RequestCultureProviders = new IRequestCultureProvider[] { new RouteDataRequestCultureProvider { IndexOfCulture = 1, IndexofUiCulture = 1 } };
   });
   services.Configure<RouteOptions>(options =>
   {
    options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint));
   });
   services.AddControllers();
  }

stay Startup.cs ClassConfigureMethod to add the request localization middleware.


 var localizeOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
   app.UseRequestLocalization(localizeOptions.Value);

RequestCultureProviderIt uses a simple delegate to determine the current localization culture. Of course, we can also use theRequestCultureProviderCustom source request area information such as configuration file or database is OK. Or we can choose some default methods to let us get the current region

ASP.NET By default, core localization provides us with four ways to determine the current culture of the request being executed:

  • QueryStringRequestCultureProvider
  • CookieRequestCultureProvider
  • AcceptLanguageHeaderRequestCultureProvider
  • CustomRequestCultureProvider

As shown below, I will determine the current area by routing


public class RouteDataRequestCultureProvider : RequestCultureProvider
 {
  public int IndexOfCulture;
  public int IndexofUiCulture;

  public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
  {
   if (httpContext == null)
    throw new ArgumentNullException(nameof(httpContext));
   string uiCulture;

   string culture = uiCulture = httpContext.Request.Path.Value.Split('/')[IndexOfCulture];

   var providerResultCulture = new ProviderCultureResult(culture, uiCulture);

   return Task.FromResult(providerResultCulture);
  }
 }

Through the following code fragmentIRouteConstraintMake corresponding constraints on routing


 public class LanguageRouteConstraint : IRouteConstraint
 {
  public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
  {

   if (!values.ContainsKey("culture"))
    return false;

   var culture = values["culture"].ToString();
   return culture == "en-us" || culture == "zh-cn";
  }
 }

Add area resource file

injectionIStringLocalizer<T>StringLocalizerMap the value of the shared resource (T) passed through to the resource file, and localization returns the value of the response from the resource file based on the name of the string


 [Route("{culture:culture}/[controller]")]
 [ApiController]
 public class HomeController : ControllerBase
 {
  private readonly IStringLocalizer<Resource> localizer;
  public HomeController(IStringLocalizer<Resource> localizer)
  {
   this.localizer = localizer;
  }
  public string Get()
  {
   return localizer["Home"];
  }
 }

As shown in the figure below

Reference

https://github.com/hueifeng/BlogSample/tree/master/src/LocalizationSingleResx

This is about ASP.NET Core webapi localization (single resource file) article introduced this, more related ASP.NET For the localization content of core webapi, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!