There are two things to do in order to get the Geo location of a request client.
1, Get the IP address of the request using below code...
string strClientIP = Request.ServerVariables["REMOTE_ADDR"].Trim();
2, Get the country code by calling free webservice, as an example, I am using freegeoip.appspot.com.
private string GetGeoLocationByIP(string strIPAddress)
{
//Create a WebRequest
WebRequest rssReq = WebRequest.Create("http://freegeoip.appspot.com/xml/" + strIPAddress);
//Create a Proxy
WebProxy px = new WebProxy("http://freegeoip.appspot.com/xml/" + strIPAddress, true);
//Assign the proxy to the WebRequest
rssReq.Proxy = px;
//Set the timeout in Seconds for the WebRequest
rssReq.Timeout = 2000;
try
{
//Get the WebResponse
WebResponse rep = rssReq.GetResponse();
//Read the Response in a XMLTextReader
XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());
//Create a new DataSet
DataSet ds = new DataSet();
//Read the Response into the DataSet
//<Status>true</Status>
//<Ip>72.14.247.141</Ip>
//<CountryCode>US</CountryCode>
//<CountryName>United States</CountryName>
//<RegionCode>CA</RegionCode>
//<RegionName>California</RegionName>
//<City>Mountain View</City>
//<ZipCode>94043</ZipCode>
//<Latitude>37.4192</Latitude>
//<Longitude>-122.057</Longitude>
ds.ReadXml(xtr);
DataTable dt = ds.Tables[0];
if (dt != null && dt.Rows.Count > 0)
{
if(dt.Rows[0]["Status"].ToString().Equals("true",StringComparison.CurrentCultureIgnoreCase))
{
return dt.Rows[0]["CountryCode"].ToString();
}
}
return String.Empty;
catch
{
return String.Empty;
}
}