Как получить данные Json с IPinfodb.com с помощью MVC WebService / Method - PullRequest
1 голос
/ 24 сентября 2010

Я хочу получить местоположение пользователя на основе IP.Когда пользователь заходит на сайт

, я делал это с XMLHTTPREquest в классическом asp

, как это сделать с .net MVC.

Я новичок в .net

1 Ответ

0 голосов
/ 24 сентября 2010

Комбинация классов WebClient и JavaScriptSerializer может помочь вам.Как всегда, начните с определения класса, который будет представлять вашу модель:

public class LocationResult
{
    public string Ip { get; set; }
    public string Status { get; set; }
    public string CountryCode { get; set; }
    public string CountryName { get; set; }
    public string RegionCode { get; set; }
    public string RegionName { get; set; }
    public string City { get; set; }
    public string ZipPostalCode { get; set; }
    public float Latitude { get; set; }
    public float Longitude { get; set; }
}

, а затем вызовите службу и десериализуйте результат JSON обратно в вашу модель:

public LocationResult GetLocationInfo(string ip)
{
    using (var client = new WebClient())
    {
        // query the online service provider and fetch the JSON
        var json = client.DownloadString(
            "http://ipinfodb.com/ip_query.php?ip=" + ip + 
            "&output=json&timezone=false"
        );

        // use the JavaScriptSerializer to deserialize the JSON
        // result back to a LocationResult
        var serializer = new JavaScriptSerializer();
        return serializer.Deserialize<LocationResult>(json);
    }
}
...