skip to Main Content

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


  1. Chosen as BEST ANSWER

    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

    // Get the current URL
    string currentUrl = Url.ActionContext.HttpContext.Request.GetEncodedUrl();
    
    // Determine the opposite language code based on the current culture
    string oppositeLanguage = currentCulture == "en" ? "de" : "en";
    
    // Replace the language code in the URL
    string newUrl = currentUrl.Replace($"/{currentCulture}/", $"/{oppositeLanguage}/");
    

  2. 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:

    public class LanguageRedirectMiddleware
    {
        private readonly RequestDelegate _next;
    
        public LanguageRedirectMiddleware(RequestDelegate next)
        {
          _next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            string lang = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
    
            // Check if the language is supported
            if (lang == "en" || lang == "de")
            {
                // Construct the language-specific URL based on the user's  language preference
                string url = $"/{lang}/{context.Request.Path}{context.Request.QueryString}";
    
                // Redirect to the language-specific URL
                context.Response.Redirect(url);
                return;
            }
    
            // Language is not supported, continue processing the request
            await _next(context);
        }
    }
    

    and in your startup.cs :

    app.UseMiddleware<LanguageRedirectMiddleware>();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search