I have localized a website in English and German and I need to display an alternate language in the HTML head section for SEO. For example, if a user is browsing the English version I need to add an alternate link to the German version in view.
string currentCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
@if (currentCulture == "en")
{
<link rel="alternate" href="https://example.com/de/" hreflang="de" />
}
else if (currentCulture == "de")
{
<link rel="alternate" href="https://example.com/en/" hreflang="en" />
}
The problem is that I can get currentUrl
but don’t know how to replace language part of URL to be set to opposite language.
When browsing english version currentUrl = https://example.com/en/contact/ so I need to replace /en/
part with /de/
Looking for nicest way to do this.
2
Answers
Thanks but I found in meantime solution so that I can resolve issue in View. I'm not redirecting to url, just use it in html code
Ok since you cannot change URL as this is part of the request, what you can do is redirect to URL with correct language. Example by doing something like this:
and in your startup.cs :
app.UseMiddleware<LanguageRedirectMiddleware>();