1
我想基于IP获取用户的位置。当用户进入网站如何使用MVC WebService /方法从IPinfodb.com获取Json数据
我曾经使用XMLHttpRequest做在传统的ASP
如何与.NET MVC做到这一点。
我是新来的.NET
我想基于IP获取用户的位置。当用户进入网站如何使用MVC WebService /方法从IPinfodb.com获取Json数据
我曾经使用XMLHttpRequest做在传统的ASP
如何与.NET MVC做到这一点。
我是新来的.NET
的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);
}
}