Sunday 12 May 2013

Get city,state,country from ip address in asp.net c# service



IpAddress = HttpContext.Current.Request.UserHostAddress.ToString();
                List<LocationbyIp> l = (GetGeoLocation(IpAddress));



private static List<LocationbyIp> GetGeoLocation(string ipaddress)
    {

        string APIKey = "7ecaaa8486a31ae8ac36a09c84ffc4c2783552766804c8f351b1f43dc096b26f";
        string url = string.Format("http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=json", APIKey, ipaddress);
        using (WebClient client = new WebClient())
        {
            string json = client.DownloadString(url);
            LocationbyIp location = new JavaScriptSerializer().Deserialize<LocationbyIp>(json);
            List<LocationbyIp> locations = new List<LocationbyIp>();
            locations.Add(location);
            return locations;

        }
    }
///////////////// Entity ///////

public class LocationbyIp
{

    public string IPAddress { get; set; }
    public string CountryName { get; set; }
    public string CountryCode { get; set; }
    public string CityName { get; set; }
    public string RegionName { get; set; }
    public string ZipCode { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public string TimeZone { get; set; }
public LocationbyIp()
{
//
// TODO: Add constructor logic here
//
}
}

No comments:

Post a Comment