Localization
Runs on your machineResponds in the language preferred by the user.
This sample runs on your machine only. The server of this website runs without culture data (in globalization-invariant mode), so it cannot switch languages.
Clone GenHTTP, let Playground/Program.cs serve LocalizationSample.Create() and start it with dotnet run - then try the commands below.
using System.Globalization;
using GenHTTP.Api.Content;
using GenHTTP.Modules.Functional;
using GenHTTP.Modules.I18n;
using GenHTTP.Modules.Layouting;
public static class LocalizationSample
{
public static IHandlerBuilder Create()
{
/*
*
* Greets users in their preferred language and formats dates the way
* they are used to. The language is taken from the "lang" query parameter
* or the Accept-Language header sent by the browser.
*
* See https://genhttp.org/documentation/content/concerns/localization/
*
*/
var greetings = new Dictionary<string, string>
{
["en"] = "Hello",
["de"] = "Hallo",
["fr"] = "Bonjour"
};
var greeting = Inline.Create()
.Get(() =>
{
var culture = CultureInfo.CurrentCulture;
return $"{greetings[culture.TwoLetterISOLanguageName]}! {DateTime.Now.ToString("D", culture)}";
});
var localization = Localization.Create()
.FromQuery("lang")
.FromHeader()
.Supports(culture => greetings.ContainsKey(culture.TwoLetterISOLanguageName)) // accepts regional variants such as de-CH
.Default(CultureInfo.GetCultureInfo("en"))
.Setter(currentCulture: true, currentUiCulture: true);
return Layout.Create()
.Add("greeting", greeting) // GET http://localhost:8080/greeting/?lang=fr
.Add(localization);
}
}Try it
With the sample running on your machine:
Prefer Swiss German
curl -i -H "Accept-Language: de-CH, en;q=0.8" http://localhost:8080/greeting/Choose French
curl -i http://localhost:8080/greeting/?lang=frPrefer Japanese
Not supported, falls back to English
curl -i -H "Accept-Language: ja" http://localhost:8080/greeting/