Search code examples
sitecoresitecore8sitecore-mvcsitecore8.1

How Do I Reset Language to Default Language


I added code to change the language to default website language if there is no language in the URL. so if i am on danish website : http://mywebsite/da then I removed the language code "da", i am switching to the default website language which is English.

The issue is on some pages it needs second page refresh to set the language to default website language, even in the cookie language is changed correctly. this is my code:

I created module for that, so in web.config I added this int the end under system.webServer/modules :

<add name="ResetLanguageModule" type="MyWebsite.Modules.ResetLanguageModule, MyWebsite.Web" />

My Code :

public void Init(HttpApplication app)
{
    app.BeginRequest += Application_BeginRequest;
}

private static void Application_BeginRequest(object sender, EventArgs e)
{
    // if user is on the root or the url does not contians language in url
    if (HttpContext.Current.Request.RawUrl == "/" || !HttpContext.Current.Request.RawUrl.Contains(string.Format("/{0}/", Sitecore.Context.Language.Name)))
    {
        ResetLanguage();
    }
}
private static void ResetLanguage()
{
    // change language to default one if the comming request is a page.
    if (Sitecore.Context.Page != null &&
        Sitecore.Context.Site != null &&
        Sitecore.Context.Language.Name != Sitecore.Context.Site.Language)
    {
        Language currentSiteLanugage;
        if (Language.TryParse(Sitecore.Context.Site.Language, out currentSiteLanugage))
        {
            Sitecore.Context.SetLanguage(currentSiteLanugage, true);
        }
    }
}

Solution

  • You should convert your module into a processor and add it to the httpRequestBegin pipeline.

    Make sure you you add it before default Sitecore LanguageResolver.