How To Find The Current Users Country using GeoLocation In EPiServer

When you install the EPiServer, if you look in your App_data folder you should see a file called GeoLiteCity.dat. This file is a IP geolocation database created by a company called MaxMind.  This means you can get the current user’s IP address and get a country code in return.

If you are running a multi language site, you can use this feature to re-direct a user to the correct language version for their country, automatically, instead of making them manually change it.  If you haven’t read my article An Alternative EPiServer Multi-Lingual Approach, that details a good use for using the GeoIp Locator.  Another good example would be setting a default currency on a commerce site.

To start using GeoLocation look-ups in your code you will need to use the

using EPiServer.Personalization;
using EPiServer.Personalization.Providers.MaxMind;
Geolocation.Provider as GeolocationProvider
public static IGeolocationResult  GetCurrentUsersLocation()
{
var geoLocationProvider = Geolocation.Provider as GeolocationProvider;
var ipAddress = GetUsersIp();
return geoLocationProvider.Lookup(ipAddress)
}
protected string GetUsersIp()
{
if (context == null || context.Request == null)
return string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
if (HttpContext.Current.Request.UserHostAddress.Length != 0)
return HttpContext.Current.Request.UserHostAddress;
return string.Empty;
}

After you have a IGeolocationResult you can get a lot of useful information from it.

Get a user’s country code

var result =  GetCurrentUsersLocation();
result.CountryCode;

Get a user’s region

var result =  GetCurrentUsersLocation();
result.Region;

Get a user’s continent

var result =  GetCurrentUsersLocation();
result.ContinentCode;

Conclusion

As Episerver provides an API and the GeoLiteCity database out the box, getting location information about a user is pretty straightforward.  You create an instance of GeolocationProvider and pass in the current user’s Ip address. The Api will return an IGeolocationResult.  From IGeolocationResult you can get information such as continent code, country code, region and location

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *