Skip to content

Instantly share code, notes, and snippets.

@keyan1603
Created September 20, 2023 18:24
Show Gist options
  • Save keyan1603/0eb93b0510b0f9057b7f41948c953124 to your computer and use it in GitHub Desktop.
Save keyan1603/0eb93b0510b0f9057b7f41948c953124 to your computer and use it in GitHub Desktop.
Get a User’s country in Sitecore using Sitecore GeoIP feature
public string GetCountry()
{
var country = Sitecore.Analytics.Tracker.Current.Interaction.GeoData.Country;
if(string.IsNullOrWhiteSpace(country))
{
return GetCountryByIp();
}
return country;
}
public string GetCountryByIp(string ipAddress = null)
{
var country = string.Empty;
try
{
// If IP address is not provided, get the IP address of the user.
ipAddress = string.IsNullOrWhiteSpace(ipAddress) ? GetIpAddress() : ipAddress;
var geoIpManager = ServiceLocator.ServiceProvider.GetRequiredService<IGeoIpManager>();
var geoIpFetchedData = geoIpManager?.GetGeoIpData(ipAddress);
if (geoIpFetchedData != null
&& geoIpFetchedData.Status == GeoIpFetchDataStatus.Fetched
&& geoIpFetchedData.WhoIsInformation != null)
{
country = geoIpFetchedData.WhoIsInformation.Country;
}
}
catch (Exception)
{
// Handle the exceptions
}
return country;
}
private string GetIpAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
// Sometimes, IP address will be present in the 'HTTP_X_FORWARDED_FOR'
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrWhiteSpace(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
// Can add several other ways to get the IP address if required including IPv6 format
// refer : https://stackoverflow.com/questions/19285957/how-to-get-the-public-ip-address-of-a-user-in-c-sharp
return context.Request.ServerVariables["REMOTE_ADDR"];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment