title: ASP.NET Core localization from unique JSON resource
body: <p>I am working on an ASP.NET Core (.NETCoreApp 1.1) web application with several views (including partial shared ones) and controllers that requires localization.</p>
  
  <p>The constraint is that the localization strings are inside a single JSON file that has the following structure (can be changed as long as it remains in one single file):</p>
  
  <pre><code>{
    "HELLO": {
      "en": "Hello!",
      "fr": "Bonjour !"
    }
  }
  </code></pre>
  
  <p>So I guess what I need is the localization to access this unique file and provide <code>IStringLocalizer</code> and <code>IViewLocalizer</code> objects that I can use in my controllers and views like <code>_localizer["HELLO"]</code>, obviously it is not the default pattern.</p>
  
  <p>To add difficulty to this, I also need to be able to automatically detect the preferred language from the browser by default or explicitly take a language as a route value, for instance /en/Home/Index or /fr/Home/Index but also /Home/Index.</p>
  
  <p>I am very new to ASP.NET Core and even with the documentation and various example achieving bits or what I need I haven't been able to implement anything reliable that I can use in production. Everything I came across has either something missing or is somehow outdated.</p>
  
  <p>I would be grateful if someone who understand those things could show me how to do this!</p>
  
  <p>Edit: I think I have figured out how to get the language from the route or from the browser if nothing in route. Here is what I did:</p>
  
  <p>My route template is <code>template: "{lang?}/{controller=Home}/{action=Index}/{id?}")</code> and here is the code I use to get the lang from a controller:</p>
  
  <pre><code>string lang = this.RouteData.Values["lang"] as string;
  if (lang == null)
  {
      string userLangs = HttpContext.Request.Headers["Accept-Language"].ToString();
      lang = userLangs.Split(',').FirstOrDefault();
  }
  </code></pre>