Search code examples
c#stringasp.net-corelocalizationsubstring

.NET core strip and replace part of URL


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.


Solution

  • 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>();