Many businesses require to implements GEO IP Services. Business Rules differ between locations. As Developers, Sitecore makes our lives easier by providing a Service that we can use to obtain the location of the website’s visitor.

The IP Geolocation provides information like country, state, city, and every visitor’s registered company name as well. Based on geodata, we can build modules that interact with our visitors and provide accurate information depending on where they are.

Installation and Configuration

Here you will find the official link to activate and set up the Sitecore IP Geolocation: Set up Sitecore IP Geolocation

In your Siecore Solution ensure you add the following Nuget Packages:

  • Sitecore.Kernel
  • Sitecore.Analytics

Solution

Sometimes when you work with lower environments or your local environment Geo IP is not available. I developed the following simple class to get the visitor’s country and city. We can add the next file to setup a city and country code when Sitecore IP Geolocation is not available for your local. I used Sitecore 10.2.


<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:env="http://www.sitecore.net/xmlconfig/env/">
  <sitecore>
    <settings env:require="Local">
      <setting name="Dev.IPGeolocation.IsDevMode" value="true"/>
      <setting name="Dev.IPGeolocation.City" value="Boston"/>
      <setting name="Dev.IPGeolocation.CountryCode" value="US"/>
    </settings>
  </sitecore>
</configuration>

The next class contains a method GetUserGeolocation to get user location information.

Noticed IGeoIPManager is injected on the constructor class.

 public class GeolocationService : IGeolocationService
    {
        private readonly IGeoIpManager _geoIpManager;

        public GeolocationService(IGeoIpManager geoIpManager)
        {
            _geoIpManager = geoIpManager;
        }
        /// <summary>
        /// Get User IP form Request Context.
        /// </summary>
        /// <returns>(string) IP Address</returns>
        private static string GetUserIP()
        {
            var ip = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
                      && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
                : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (ip.Contains(","))
                ip = ip.Split(',').First().Trim();

            return ip.Trim();
        }

        /// <summary>
        ///   Fetch country from Sitecore IP Geolocation Service check 
        ///   setup at https://doc.sitecore.com/developers/93/sitecore-experience-manager/en/set-up-sitecore-ip-geolocation.html
        /// </summary>
        /// <returns></returns>
        public GeoData GetUserGeolocation()
        {
            GeoData geoData;
            bool IsDevEnviroment = Settings.GetBoolSetting("Dev.IPGeolocation.IsDevMode", false);
            if (!IsDevEnviroment)
            {
                try
                {
                    var result = _geoIpManager.GetGeoIpData(GetUserIP());
                    if (result.Status == GeoIpFetchDataStatus.Fetched &&
                        result.WhoIsInformation != null)
                    {
                        geoData = new GeoData()
                        {
                            City = result.WhoIsInformation.City,
                            CountryCode = result.WhoIsInformation.Country
                        };
                    }
                    else
                    {
                        throw new Exception("GeoIP whoIsInformation is null");
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Error Getting IPAddress", e, typeof(GeolocationService));
                    if (Tracker.Current != null && Tracker.Current.Interaction != null && Tracker.Current.Interaction.GeoData != null)
                    {
                        geoData = new GeoData()
                        {
                            City = Tracker.Current.Interaction?.GeoData?.City,
                            CountryCode = Tracker.Current.Interaction?.GeoData?.Country
                        };

                    }
                    else
                    {
                        Log.Error("IPGeolocation: There is an issue with IP Geolocation Service", typeof(GeolocationService));
                        geoData = new GeoData()
                        {
                            City = null,
                            CountryCode = Settings.GetSetting("LocationEngine.IPGeolocation.CountryCode")
                        };
                    }
                }

            }
            else
            {
                Log.Info("IPGeolocation: Dev Mode is enabled", typeof(GeolocationService));
                geoData = new GeoData()
                {
                    City = Settings.GetSetting("Dev.IPGeolocation.City"),
                    CountryCode = Settings.GetSetting("Dev.IPGeolocation.CountryCode")
                };
            }
            Log.Info($"IPGeolocation: Country Code is {geoData.CountryCode}", typeof(GeolocationService));
            return geoData;
        }
    }

Finally, GeoData is a model class that contains the location information.


 public class GeoData
    {
        public string CountryCode { get; set; }
        public string City { get; set; }
    }

I hope this information will be usefully when you work with Sitecore Geo IP Services.