This is the code that I have at the moment and which throws that exception explained previously.
protected override async Task OnParametersSetAsync()
{
var languageFromURL = string.Empty;
var languageFromCulture = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
var parts = _navigationManager.ToBaseRelativePath(_navigationManager.Uri.ToString()).Split('/');
if (parts.Count() > 1)
{
languageFromURL = parts[0];
PageName = parts[1];
}
try
{
// ensure that language is two letters
if (languageFromCulture.Length == 2 && languageFromURL.Length == 2)
{
if (languageFromURL != languageFromCulture)
{
//-- LANGUAGE IN THE URL DIFFERS FROM THE CURRENTLY SELECTED LANGUAGE
var isPastedRouteFound = false;
var newLanguage = string.Empty;
var newRoute = string.Empty;
using (Microsoft.Data.SqlClient.SqlConnection connection = DatabaseHelpers.NewConnection())
{
connection.Open();
using (Microsoft.Data.SqlClient.SqlCommand command = connection.CreateCommand())
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "blazor_CheckRoute";
command.Parameters.AddWithValue("@LanguageFromCulture", languageFromCulture); // language from the culture info
command.Parameters.AddWithValue("@LanguageFromURL", languageFromURL); // language from the route/URL
command.Parameters.AddWithValue("@PageName", PageName);
command.Parameters.Add("@IsRouteFound", System.Data.SqlDbType.Int, 4).Direction = System.Data.ParameterDirection.Output;
command.ExecuteNonQuery();
if (command.Parameters["@IsRouteFound"].Value != null)
{
isPastedRouteFound = Convert.ToBoolean(command.Parameters["@IsRouteFound"].Value);
}
}
}
if (isPastedRouteFound == true)
{
var culture = string.Empty;
switch (languageFromURL)
{
case "en":
culture = Uri.EscapeDataString("en-US");
break;
case "de":
culture = Uri.EscapeDataString("de-DE");
break;
case "es":
culture = Uri.EscapeDataString("es-ES");
break;
}
_httpContextAccessor.HttpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture, culture)));
//-- EXCEPTION IS THROWN WHEN THE LINE BELOW GETS EXECUTED
//_navigationManager.NavigateTo(_navigationManager.Uri, true);
}
}
}
}
catch (Exception ex)
{
Logging.LogError(ex, remark: "");
}
await Task.CompletedTask;
}
Database Table (Pages)
Language Route
en contact
de kontakt
es contacto
etc. etc.
Possible scenario: let's say you are currently visiting website.com/es/contacto. Then you paste the following URL to the address bar and hit enter: website.com/en/contact. It redirects you to the new route but the page remains in Spanish. Then if you navigate to another page the language gets changed to EN.
I am certain that I miss something obvious though I am not quite sure what. Thank you!