I am trying to deliver automatic language selection using localization, dependent on the Domain/TLD, under Blazor Server .NET8. My site uses the same codebase for two different domains - mysite.com and mysite.kh - and the correct language needs to be selected before the first rendering of the site to ensure the SEs index the correct content. I am assuming that this needs to be set within program.cs - but it is not possible to use NavigationManager there to ascertain the domain name. I am assuming I need something like this within program.cs...
if (thisdomain = "mydomain.com")
{
string[] supportedCultures = ["en-US", "ko-KR"];
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
}
else if (thisdomain = "mydomain.kr")
{
string[] supportedCultures = ["ko-KR", "en-US"];
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
}
...but I can't find any information on how I can establish the domain name within program.cs prior to Localization initiation - any help would be greatly appreciated.
This was the solution I found:
public class RouteCultureProvider : IRequestCultureProvider
{
public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
string culture = "";
var url = httpContext.Request.GetDisplayUrl().ToLower();
var tld = "";
if (url.Contains("mysite.com"))
{
tld = "com";
}
else if (url.Contains("mysite.kr"))
{
tld = "kr";
}
switch (tld)
{
case "kr":
culture = "ko";
break;
case "com":
default:
culture = "en-GB";
break;
}
return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(culture, culture));
}
}
...called from the localization setup within Program.cs:
string[] supportedCultures = ["en-GB", "ko"];
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
//pull in the correct default culture based on the URL which is resolved in RouteCultureProvider
localizationOptions.RequestCultureProviders.Insert(0, new
RouteCultureProvider());
localizationOptions.SetDefaultCulture(supportedCultures[0]);
Here I employed middleware (RouteCultureProvider) which is called from Program.cs, and does the job of establishing the TLD of the calling URL, and passes back the default culture based on this, which is then set as default.
Based on to rdhainaut's answer to this question - tweaked for Blazor Server & .net8 - kudos to you, many thanks!