Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

Sitecore: MaxMind GeoIP api and caching

Modified: 2015/01/27 08:56 by vanthoog - Categorized as: Sitecore
Sitecore Analytics (a.k.a. DMS) comes with the ability to determine the visitor’s location based on their IP address. Behind the scenes this service is actually provided by MaxMind. More information can be found at MaxMind - Sitecore integrated service.

Suppose you want to use this logic within your own code. You can request the location data (e.g. the country) of the current visitor by using the following lines of code:


	Sitecore.Analytics.Lookups.MaxMindProvider maxMindProvider = new Sitecore.Analytics.Lookups.MaxMindProvider();
	Sitecore.Analytics.Lookups.WhoIsInformation geoIpInformation = maxMindProvider.GetInformationByIp(Request.ServerVariables["REMOTE_ADDR"]);
	string country = geoIpInformation.Country;

Nice and easy, nothing special.

This code fragment has however one disadvantage: for every visit the MaxMind service will be contacted. This is undesirable because the MaxMind licensing scheme is based on number of visits. So, if your site attracts a lot of visitors, you will soon have to purchase a more expensive MaxMind license. To avoid this, you will have to build in a caching mechanism. The good news is that Sitecore has already implemented such a caching mechanism! Use the following code fragment instead:

	System.Net.IPAddress ipAddress = null;

	if (System.Net.IPAddress.TryParse(Request.ServerVariables["REMOTE_ADDR"], out ipAddress))
	{
		Sitecore.Analytics.Lookups.GeoIpOptions geoIpOptions = new Sitecore.Analytics.Lookups.GeoIpOptions();
		geoIpOptions.Ip = ipAddress;
		geoIpOptions.MillisecondsTimeout = 1000;

		Sitecore.Analytics.Lookups.GeoIpResult geoIpResult = Sitecore.Analytics.Lookups.GeoIpManager.GetGeoIpData(geoIpOptions);

		if (geoIpResult != null)
		{
			string country = geoIpResult.GeoIpData.Country;
		}
	}


The MaxMind location data cache is stored within the analytics database in the table GeoIps. So even after a restart of your website the cache data is still available.

One final remark. The property MillisecondsTimeout of the class GeoIpOptions does not seem to be used. In this example it has been set to 1000 but this does not seem to have any effect.

Note: This information is based on Sitecore v7.2.

 © Evident Interactive BV