c#根据ip获取地理位置
前端js
var shs=""; var shis=""; $(function () { $.ajax({ type: "POST", url: "/api/LBCitys/GetAddrs" }) .success(function (result) { console.log(result); if(result!="") { shs=result.split("-")[0]; shis=result.split("-")[1]; } });
后端接口
[HttpPost] public string GetAddrs() { string ip = GetIpAddress.GetUserIp(); string jsonstr = HttpGet("http://api.map.baidu.com/location/ip?ak=rg3c2fj4QBZwa6v3h1w95Sp9&ip=" + ip); JObject jo = (JObject)JsonConvert.DeserializeObject(jsonstr); string json = jo.ToString();//JObject 转json字符串 //return json; string addr=""; try { addr = jo["content"]["address_detail"]["province"].ToString() + "-" + jo["content"]["address_detail"]["city"].ToString(); }catch(Exception ex){ addr = ""; } return addr; }