我如何获得用户IP和国家/地区名称 [英] How I get user IP and country name

查看:89
本文介绍了我如何获得用户IP和国家/地区名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void GetIpLocation()
        {

            string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ipAddress))
            {
                ipAddress = Request.ServerVariables["REMOTE_ADDR"];
            }

            string APIKey = "e56f667f98265912bc0fa937413351933be9d3e15aeee6448b3d8443e8d47c48";
            string url = string.Format("http://api.ipinfodb.com/v3/ip-city/?key=e56f667f98265912bc0fa937413351933be9d3e15aeee6448b3d8443e8d47c48&format=json", APIKey, ipAddress);
            using (WebClient client = new WebClient())
            {
                string json = client.DownloadString(url);
                Location location = new JavaScriptSerializer().Deserialize<location>(json);
                List<location> locations = new List<location>();
                locations.Add(location);

                gvLocation.DataSource = locations; // bind data in gridview
                gvLocation.DataBind();


            }

        }





我是什么尝试过:



我已经在我的本地计算机上获取了所有数据。但是当我生活我的代码然后返回服务器IP和国家。我想要用户他使用我的网站时的数据。这是我在C#中的代码



What I have tried:

I have already get all data on my local computer.But when I live my code then return Server IP and Country.I want User data when he use my website.This is my code in C#

推荐答案

引用:




string url = string.Format("http" + "://api.ipinfodb.com/v3/ip-city/?key=e56f667f98265912bc0fa937413351933be9d3e15aeee6448b3d8443e8d47c48&format=json", APIKey, ipAddress);






有问题 - 您的格式字符串不包含参数的任何占位符,因此您需要检索IP地址的信息发出请求的计算机。



更改字符串以包含API密钥和IP地址的占位符:


There's your problem - your format string doesn't contain any placeholders for the parameters, so your retrieving the information for the IP address of the computer making the request.

Change the string to include placeholders for the API key and IP address:

string url = string.Format("http" + "://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=json", APIKey, ipAddress);





注意:我必须添加+来分解网址,以防止网站在其周围插入< a> 标记。您不需要在代码中包含它。



NB: I've had to add a " + " to break up the URL, to prevent the site from inserting <a> tags around it. You don't need to include that in your code.


请参见此处:使用基于IP的地理定位 - 以及为什么它几乎没用。 [ ^ ] - 它会告诉你如何做到这一点,以及解释为什么它是几乎浪费时间......
See here: Using IP based Geolocation - and why it's pretty much useless.[^] - it shows you how to do it, along with explainign why it's pretty much a waste of time...


这篇关于我如何获得用户IP和国家/地区名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆