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);
}
}