2017-03-07 42 views
0

拳头在所有抱歉为我的坏英语。从客户端获取IP信息到Web Api

我试图让登录选项中的IP将它们保存为数据库中的“会话”,并注册使用该应用的人和地点。

我尝试了这个,但很明显,它不会起作用。

var ip = new System.Net.WebClient().DownloadString("http://ipinfo.io/json"); 

它获取IP客户端。因此,我需要在客户方面做到这一点。但问题是,客户可以更改此值,其之前发送到Web API

$http.get("http://ipinfo.io/json").then(function (response) { 
    return response.data; 
}).catch(function (response) { 
    console.log(response.data); 
}); 

用户可以修改这个值给我虚假数据在登录和我没有如何验证,如果这些信息是有效的或真实的。所以,问题是¿我如何在不让用户操纵这些数据的情况下做到这一点?

+0

不是向http://ipinfo.io/json您应该请求http://ipinfo.io/ /JSON作为每https://ipinfo.io/developers在服务器上的 –

回答

0

在web API中创建一个方法,我们可以将所有需要的信息直接保存到数据库中。

public static string UserIp() 
     { 
      string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
      if (string.IsNullOrEmpty(ip)) 
      { 
       ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; 
      } 

      try 
      { 
       string url1 = "http://geoip.nekudo.com/api/" + ip.ToString(); // passing IP address will return location information. 
       WebClient client = new WebClient(); // Intialize the webclient 
       string jsonstring = client.DownloadString(url1); 
       dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); // De-serialize the JSON string 
       string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "Ip.txt"; 
       using (System.IO.StreamWriter writer = new StreamWriter(filePath, true)) 
       { 
// you can save the information to database instead of writing to a file 

        writer.WriteLine("UserIp:" + ip); 
        writer.WriteLine("Date:" + DateTime.Now); 
        writer.WriteLine("JsonString:" + jsonstring); 
        writer.WriteLine("Country name:" + dynObj.country.code); 

       } 

       return dynObj; 


      } 
      catch (Exception ex) 
      { 
       string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "I.txt"; 
       string url1 = "http://geoip.nekudo.com/api/" + ip.ToString(); 
       WebClient client = new WebClient(); // Intialize the webclient 
       string jsonstring = client.DownloadString(url1); 
       dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); 
       // string a = dynObj.country.code; 
       using (System.IO.StreamWriter writer = new StreamWriter(filePath, true)) 
       { 
        writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + 
            ex.StackTrace + 
            "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); 

        writer.WriteLine("UserIp:" + ip); 
        writer.WriteLine("Dynamic obj:" + dynObj); 
       } 
       return null; 
      } 


     } 
+0

是正常的在本地测试得到字符串ip =“:: 1”? –

+0

我没有得到你想说的话吗? – ISHIDA

+0

This HttpContext.Current.Request.ServerVariables [“HTTP_X_FORWARDED_FOR”];让我空。 This HttpContext.Current.Request.ServerVariables [“REMOTE_ADDR”];让我“”1“作为价值。 –