Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.NET core strip and replace part of URL

I have localized website in English and German and I need to display alternate language in html head section for SEO. For example if user is browsing English version I need to add alternate link to 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/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading