一、获取IP常用方法
public class BaseAPIController : ApiController { ///获取客户端访问IP /// protected string CurrentUserIP { get { string realRemoteIP = ""; if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) { realRemoteIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',')[0]; } if (string.IsNullOrEmpty(realRemoteIP)) { realRemoteIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (string.IsNullOrEmpty(realRemoteIP)) { realRemoteIP = System.Web.HttpContext.Current.Request.UserHostAddress; } return realRemoteIP; } } }
1、返回需要的参数类 position
[Serializable] public class Position { public string address { get; set; } public Content content { get; set; } public int status { get; set; } } public class Content { public string address { get; set; } public Address_detail address_detail { get; set; } public Point point { get; set; } } public class Address_detail { public string city { get; set; } public int city_code { get; set; } public string district { get; set; } public string province { get; set; } public string street { get; set; } public string street_number { get; set; } } public class Point { public string x { set; get; } public string y { set; get; } }
2、调取接口接受返回数值
WebClient wc = new WebClient(); string jsonStr = wc.DownloadString("http://api.map.baidu.com/location/ip?ak=8aa60008a5478bc272e4cb098567a382&ip=" + Common.Common.GetUserIp() + ""); Position p = new Position(); try { JavaScriptSerializer jss = new JavaScriptSerializer(); p = (Position)jss.Deserialize(jsonStr, typeof(Position)); } catch (Exception e) { ViewBag.ID = 3270; ViewBag.Name = "北京"; } if (p.status != 0 || p.content.address_detail.city == "")//出错 { ViewBag.ID = 3270; ViewBag.Name = "北京"; } else { string cityName = p.content.address_detail.city; int cityIndex = Bu.AreaBLL.GetCityIndexByName(cityName,2); if (cityIndex == 0)//数据库没有该城市 { ViewBag.ID = 3270; ViewBag.Name = "北京"; } else { ViewBag.ID = cityIndex; ViewBag.Name = p.content.address_detail.city.Replace("市", ""); } }