I\'m looking for ways to detect/estimate the country from which a http-request is coming in ASP.NET.
I know there are
I just had to do this so here's a working example (specific to France) which may be of use to someone:
string userIP = Request.ServerVariables["REMOTE_ADDR"];
string localeAPIURL = "http://api.hostip.info/get_html.php?ip=" + userIP;
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(localeAPIURL);
r.Method = "Get";
HttpWebResponse res = (HttpWebResponse)r.GetResponse();
Stream sr = res.GetResponseStream();
StreamReader sre = new StreamReader(sr);
// check response for FRANCE
string s = sre.ReadToEnd();
string sub = s.Substring(9, 6);
if (sub == "FRANCE")
{
Response.Redirect("http://fr.mysite.com");
}
This is what I've used:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
'url': 'http://www.freegeoip.net/json/@(HttpContext.Current.Request.UserHostAddress)',
'type': 'GET',
'success': function(data) {
// for example
if (data.country_code === "GB") {
... further logic here
}
}
});
});
</script>
Simple, and it works.
If you choose to use the REMOTE_ADDR server variable, you can be fairly certain that the IP that you recover accurately represents the nation of origin of that user. It is fairly uncommon for a user to be accessing the Internet from outside of the country that he is currently in, with a few notable exceptions, such as those who choose to surf though an anonymous proxy server, such as is discussed below. If, however, you want to get the state that a user is coming from, or authenticate the identity of a user, you're out of luck as far as any even remotely reliable method is concerned.
More info here.
You can make a simple HTTP request to this URL:
http://api.hostip.info/get_html.php?ip=207.46.197.32
using the value of the REMOTE_ADDR
server variable. That will return the country and city like this:
Country: UNITED STATES (US)
City: New York, NY
I use that service for a web form just as you describe. Occasionally it doesn't know the answer, but usually it's very good (and it's free and simple 8-)
In C#, you can use System.Net.WebRequest.Create to read from the URL.
You can use one of available web services to match an incoming request to a country.
Otherwise you may decide to grab the MaxMind database file (GeoLite Country), read from this file in your application and perform a match. Thus you will be independent from a third-party service, only pulling regularly updates for the database file.
Also check out similar questions:
Geolocation web service recommendations
Know a good IP address Geolocation Service?