根据当前IP获取当时所在信息

  现在很多系统,都要在登录时候,确定当前用户所在的位置。这里记录一个C#使用Http的方式获取当前IP所在的位置信息。主要使用的api是新浪的接口。

 1 public partial class sina : System.Web.UI.Page
 2 {
 3     protected string ip = "171.216.18.89";
 4     protected void Page_Load(object sender, EventArgs e)
 5     {
 6         //if (IPOperation.GetIP() != "127.0.0.1")
 7         //{
 8         //    ip = IPOperation.GetIP();
 9         //}
10         this.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script language='javascript' defer>alert('" + GetCityByIP(ip).ToString() + "');</script>");
11 
12     }
13     private string GetCityByIP(string ip)
14     {
15         string cityName = "成都";
16         if (!string.IsNullOrEmpty(ip))
17         {
18             string url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip;
19             HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
20             request.Method = "POST";
21             request.ContentType = "application/json;charset=utf-8";
22             Stream stream = request.GetResponse().GetResponseStream();
23             StreamReader sr = new StreamReader(stream, Encoding.UTF8);
24             string str = sr.ReadToEnd().Split('=')[1].ToString().TrimEnd(';');
25 
26 
27             IPArea list = new JavaScriptSerializer().Deserialize<IPArea>(str);
28             cityName = list.city;
29         }
30         return cityName;
31     }
32 }
33 class IPArea
34 {
35     public int ret { get; set; }
36     public string start { get; set; }
37     public string end { get; set; }
38     public string country { get; set; }
39     public string province { get; set; }
40     public string city { get; set; }
41     public string district { get; set; }
42     public string isp { get; set; }
43     public string type { get; set; }
44     public string desc { get; set; }
45 }
View Code

  主要先创建一个HttpWebRequest,定义请求方式及返回数据的结构和编码。这里使用JavaScriptSerializer将返回的json对象反序列化为对象。关于对象的信息就不记载了。

posted @ 2015-01-20 11:06  瀞默  阅读(343)  评论(2编辑  收藏  举报