我经历了这么多文件,但对我来说没什么用.我已经关注 了一个链接
我想通过IP地址获取当前用户的位置.但是,我ipAddress总是显示 null然后::1.我不知道我做错了什么.
任何人都可以帮我解决这个问题.
模型
public class LocationModel
{
public string IP { get; set; }
public string Country_Code { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
调节器
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = Request.ServerVariables["REMOTE_ADDR"];
}
LocationModel location = new LocationModel();
string url = string.Format("http://freegeoip.net/json/{0}", ipAddress);
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
location = new JavaScriptSerializer().Deserialize<LocationModel>(json);
}
return View(location);
}
}
Run Code Online (Sandbox Code Playgroud)
视图
@model IPAddress_Location_MVC.Models.LocationModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr><td>IP</td><td>@Model.IP</td></tr>
<tr><td>Country Code</td><td>@Model.Country_Code</td></tr>
</table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
正如尼勒什指出的那样;您收到的回复是有效的。::1 是 IPv6 环回地址的简称。这相当于 IPv4 127.0.0.0 或本地主机。由于您在本地运行并在本地连接,因此它会报告您的本地主机地址。如果您在不同于您自己的计算机上运行此代码,并从您自己的计算机连接到它,您将获得返回的“真实”IP。
您提到的第二点是您收到“远程服务器返回错误:(403) Forbidden”。调用 FreeGeoIP 服务时是由于该端点不再使用而导致的。(只需浏览该 URL: http: //freegeoip.net/json/)为了完整,它会返回以下消息:
重要信息 - 请更新您的 API 端点 此 API 端点已弃用,现已关闭。要继续使用 freegeoip API,请更新您的集成以使用新的 ipstack API 端点,该端点被设计为简单的直接替换。您需要在https://ipstack.com创建帐户并获取 API 访问密钥。有关如何升级的更多信息,请访问我们的 Github 教程:https://github.com/apilayer/freegeoip#readme
更新:
新的 API 格式为:
http://api.ipstack.com/IP_FOR_LOOKUP?access_key=YOUR_ACCESS_KEY&output=json&legacy=1
为了读取结果 (Json),您可以使用像 NewtonSoft 这样的 Json 反序列化器。您需要在项目中引用 Newtonsoft.Json 包并创建一个表示结果的 POCO。然后调用 Newtonsoft 将 Json 反序列化为您的对象。例如,您可以查看他们的文档。
| 归档时间: |
|
| 查看次数: |
1239 次 |
| 最近记录: |