Created
October 9, 2012 18:16
-
-
Save bradoyler/3860466 to your computer and use it in GitHub Desktop.
Locate a user (ASP.Net) using ipinfodb.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string ip = Request.ServerVariables["X-Forwarded-For"] | |
public class LocationInfo | |
{ | |
public string Country { get; set; } | |
public string RegionName { get; set; } | |
public string City { get; set; } | |
public string ZipCode { get; set; } | |
public float Latitude { get; set; } | |
public float Longitude { get; set; } | |
} | |
public static LocationInfo HostIpToPlaceName(string ip) | |
{ | |
ObjectCache cache = MemoryCache.Default; | |
var key = "zzzzzgetyourowncodezzzzzz"; | |
string url = "http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=xml"; | |
url = String.Format(url,key, ip); | |
var location = new LocationInfo(); | |
var result = cache[ip] as XDocument; | |
try | |
{ | |
if (result == null) | |
{ | |
result = XDocument.Load(url); | |
cache.Add(ip, result, | |
new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromDays(1) }); | |
} | |
location = (from x in result.Descendants("Response") | |
select new LocationInfo | |
{ | |
City = (string)x.Element("cityName"), | |
RegionName = (string)x.Element("regionName"), | |
Country = (string)x.Element("countryName"), | |
ZipCode = (string)x.Element("zipCode"), | |
Latitude = (float)x.Element("latitude"), | |
Longitude = (float)x.Element("longitude") | |
}).First(); | |
return location; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment