In this tutorial, you will learn how to set up an Episerver powered website so it works with multiple languages. This is not a content editor guide on how to configure the CMS to work with multiple languages, I assume you know that already. This guide is for developers who want to learn how to write the code required to deal with language switching on the front end. The difference in this guide is that the technique here will enforce that a user stays on a specific language version. Show those content editors whose boss 🔥🔥🔥

The first step is to set a default language cookie in the site visitors browser when they view the page. This cookie will be used to ensure the user sees the correct language version. In MVC, we can use a global ActionFilter to ensure certain functionality is executed whenever a user requests a web page from our site. In a multi-language setup, you will want to drop a language cookie within the user's browser regardless of the page that they are requesting. The custom ActionFilter will need to check if a language cookie already exists, if it doesn't, it should set a cookie based on the language version of the page the visitor is requesting. The code how to do that is shown below:

This code works great for people when they first visit the site, however, what happens when they are returning customers? If users are jumped between different versions of a page then this creates a bad user experience. When someone sets their language preference, they should always see that version, unless they choose otherwise. To make this work, you will need to write some code to always switch the language of the current request to the language set in the cookie.

You will need access to the Episerver page object within the ActionFilter in order to get the correct content. As we're in an ActionFilter the normal IContentRepsotiory is not available. Instead, you can access the current Episerver page object using this snippet:

If the value of the cookie is different to the language being requested, you will need to set the language to use the value in the cookie (the cookie value is the master value). Episerver will take care of the language switch for you. This can be done using this snippet:

Finally, we can put the complete ActionFilter togther:

On Line15, you will see a call to CookieHelper. All the vanilla cookie get and set code is done within this helper. The code for CookieHelper is shown below:

This covers all the code that you will need to write in order to set a language cookie, read that cookie on all page requests and then change the current language based on that value. In the next tutorial Creating A Multi-Language Picker In Episerver I'll explain how to create a corresponding language picker. Happy Coding 🤘