Episerver start page language based on visitor's IP

Got tasked with determining and showing start page language based on visitor's IP on a Episerver 7.13 Web Forms site.

The site has https://www.siteurl.com/ as the primary host name. The site has bindings for many names and IIS Redirecting/Rewriting for the non primary host names and misc moved URLs. The task was to do a Episerver way geolocation lookup and pass visitors with an IP in Sweden to the startpage in Swedish, https://www.siteurl.com/sv/ in this case. All other countries should get the English start page.

I looked at the initialize culture override but since the specification was to never show any content on the site url root (based on SEO advice) I just placed a call to this method in the OnLoad of my StartPage page template.

using EPiServer.Personalization;
..
private void LookupCountryAndRedirectToLanguageStart()
{
    var currentUrl = Request.Url;
    var siteUrl = SiteDefinition.Current.SiteUrl;

    // Exclude the querystring + fragment in case you want to put a mock IP or similar there
    string current = string.Concat(
                        currentUrl.Scheme,
                        currentUrl.Host,
                        currentUrl.AbsolutePath);
    string site = string.Concat(
                        siteUrl.Scheme,
                        siteUrl.Host,
                        siteUrl.AbsolutePath);

    // Should only match https://www.siteurl.com/, the prefix checks just
    // for peace of mind in regards to redirect loops
    if (current.Equals(site, StringComparison.OrdinalIgnoreCase)
        && !current.ToLower().Contains("/en/")
        && !current.ToLower().Contains("/sv/"))
    {
        // GetUserIp() is something you most likely already have in place where you look at
        // both Request.ServerVariables["HTTP_X_FORWARDED_FOR"] & Request.ServerVariables["REMOTE_ADDR"]
        var ip = Request.GetUserIp();

        if (ip != null)
        {
            IGeolocationResult loc = Geolocation.Provider.Lookup(ip);
            string countryCode = loc == null ? null : loc.CountryCode;

            if (countryCode != null)
            {
                // Should be temporary redirects here (not permanent)
                if (countryCode.Equals("SE", StringComparison.OrdinalIgnoreCase))
                {
                    Response.Redirect("/sv/", true);
                    return;
                }
            }
        }

        Response.Redirect("/en/", true);
    }
}

It works!

Published and tagged with these categories: Episerver, ASP.NET