1

我正在使用此脚本来获取用户的客户端 IP:

<script type="text/javascript" src="http://geoiplookup.wikimedia.org/"></script>

我可以使用 JavaScript as 来获取 IP Geo.IP,但我需要在按钮单击后的代码中获取它。

就像是:

protected void Button1_Click(object sender, EventArgs e)
{
    string IP = string.Empty;

    // IP = ???

    // Validation code

}

有任何想法吗?

提前致谢...

4

2 回答 2

1

为什么是客户端脚本?Request.UserHostAddress听起来像您正在寻找的东西。:)

protected void Button1_Click(object sender, EventArgs e)
{
    string IP = Request.UserHostAddress;

    // Validation code

}
于 2013-02-12T08:08:12.877 回答
0

如果您真的不能使用服务器变量,或者如果您需要地理信息以及 IP,您将需要以下内容:

<!-- Get geo information -->
<script type="text/javascript"
    src="http://geoiplookup.wikimedia.org/">
</script>
<!-- JavaScript object-to-JSON -->
<!-- Don't actually hotlink this; host it yourself -->
<script type="text/javascript" 
    src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">
</script>
<!-- Hidden field to hold result -->
<asp:HiddenField id="hdnGeo" runat="server"></asp:HiddenField>
<!-- Script to populate field -->
<script type="text/javascript">
    document.getElementById('<%= hdnGeo.ClientID %>').value =
        JSON.stringify(Geo);
</script>

这会将 Geo 对象的 JSON 等效项放在您的 geoiplookup 参考中

{"city":"London","country":"GB","lat":"51.514198","lon":"-0.093100",
 "IP":"193.129.26.250","netmask":"24"}

进入 ASP.NET 隐藏字段。

然后,在服务器上,您可以像这样访问它:

protected void Button1_Click(object sender, EventArgs e)
{
    string json = hdnGeo.Value;
    var dictionary = new JavaScriptSerializer()
        .Deserialize<Dictionary<string, string>>(json);
    string city = dictionary["city"];
    string lat = dictionary["lat"];
    string lon = dictionary["lon"];
    string IP = dictionary["IP"];
    string netmask = dictionary["netmask"];
}
于 2013-02-12T08:25:17.810 回答