From 4b431c46c9e26845e9b2f5478f2c64956c0498e7 Mon Sep 17 00:00:00 2001 From: Artur Drobinskiy Date: Thu, 25 Jul 2019 11:49:43 +0700 Subject: [PATCH] Fixes #7: NullReferenceException when using ThreadLanguageDetector and Accept-Language header is not present --- samples/Example.WebApp/Program.cs | 5 +++++ src/I18Next.Net.Extensions/Builder/I18NextOptions.cs | 2 +- src/I18Next.Net/Plugins/ThreadLanguageDetector.cs | 7 ++++++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/samples/Example.WebApp/Program.cs b/samples/Example.WebApp/Program.cs index 6e4fe87..e127db8 100644 --- a/samples/Example.WebApp/Program.cs +++ b/samples/Example.WebApp/Program.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; @@ -14,6 +16,9 @@ public class Program { public static void Main(string[] args) { + // This is usually the case for production servers + Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; + Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; CreateWebHostBuilder(args).Build().Run(); } diff --git a/src/I18Next.Net.Extensions/Builder/I18NextOptions.cs b/src/I18Next.Net.Extensions/Builder/I18NextOptions.cs index 52bd1a9..a5510e6 100644 --- a/src/I18Next.Net.Extensions/Builder/I18NextOptions.cs +++ b/src/I18Next.Net.Extensions/Builder/I18NextOptions.cs @@ -7,7 +7,7 @@ public class I18NextOptions public string DefaultLanguage { get; set; } = "en-US"; public string DefaultNamespace { get; set; } = "translation"; - public IList FallbackLanguages { get; set; } + public IList FallbackLanguages { get; set; } = new List(); public bool DetectLanguageOnEachTranslation { get; set; } } diff --git a/src/I18Next.Net/Plugins/ThreadLanguageDetector.cs b/src/I18Next.Net/Plugins/ThreadLanguageDetector.cs index f875328..e4cca5c 100644 --- a/src/I18Next.Net/Plugins/ThreadLanguageDetector.cs +++ b/src/I18Next.Net/Plugins/ThreadLanguageDetector.cs @@ -18,7 +18,12 @@ public ThreadLanguageDetector(string fallbackLanguage) public string GetLanguage() { - return Thread.CurrentThread.CurrentCulture.IetfLanguageTag; + var languageTag = Thread.CurrentThread.CurrentCulture.IetfLanguageTag; + if (string.IsNullOrEmpty(languageTag)) + { + return FallbackLanguage; + } + return languageTag; } } }