.NET Core: Set the correct CurrentCulture basing the `lang` header

  1. Create a middleware to do that task

     public static void SetCurrentCulture(this IApplicationBuilder app)
     {
         app.Use(async (context, next) =>
         {
             var cultureQuery = context.Request.Headers["lang"] == "en" ? "en-US" : "zh-CN";
             if (!string.IsNullOrWhiteSpace(cultureQuery))
             {
                 var culture = new CultureInfo(cultureQuery);
                 CultureInfo.CurrentCulture = culture;
                 CultureInfo.CurrentUICulture = culture;
             }
             await next();
         });
     }
    
  2. Use the middleware in Startup.cs

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILog logger,
         IExceptionEntityService exceptionEntityService)
     {
         ...
         app.SetCurrentCulture();
         ...
     }
    

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.