我想在ASP.NET中实现这个功能,但很遗憾我不知道该如何做。
我想在ASP.NET中实现这个功能,但很遗憾我不知道该如何做。
以下是在ASP.NET中完成此操作的方法:
Request.ServerVariables("REMOTE_ADDR")
在这里按位置获取IP地址数据库的副本
string userHost = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(userHost) ||
String.Compare(userHost, "unknown", true) == 0)
{
userHost = Request.UserHostAddress;
}
您将获得用户的IP地址。基于此IP地址,您可以通过调用一些Web服务来查找访问者的位置详细信息。
有一些免费的网络服务可以提供 IP 到位置的转换。例如:
http://freegeoip.net/
http://www.hostip.info/
http://ipinfodb.com/ip_location_api.php
首先,使用Request.ServerVariables("REMOTE_ADDR")获取访问者的IP地址。请注意,访问者可能使用代理服务器,此时IP地址可能不是他们的实际IP地址。对于代理情况,您可以检查Request.ServerVariables("HTTP_X_FORWARDED_FOR")是否包含值。如果代理服务器不是匿名代理服务器,则这将是实际的IP地址。
然后您有两个选择,使用Web服务或从自己的数据库查询数据。无论哪种方式,您都需要数据,该数据可以将访问者的IP地址与其所在国家、州和城市相匹配。
使用ipStack(https://ipstack.com)的地理位置API,我已经使用了以下内容:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
'url': 'https://www.freegeoip.net/json/@(HttpContext.Current.Request.UserHostAddress)',
'type': 'GET',
'success': function(data) {
// for example
if (data.country_code === "GB") {
... further logic here
}
}
});
});
</script>
它返回很多有用的信息,例如:
{
"ip": "134.201.250.155",
"hostname": "134.201.250.155",
"type": "ipv4",
"continent_code": "NA",
"continent_name": "North America",
"country_code": "US",
"country_name": "United States",
"region_code": "CA",
"region_name": "California",
"city": "Los Angeles",
"zip": "90013",
"latitude": 34.0453,
"longitude": -118.2413,
"location": {
"geoname_id": 5368361,
"capital": "Washington D.C.",
"languages": [
{
"code": "en",
"name": "English",
"native": "English"
}
],
"country_flag": "https://assets.ipstack.com/images/assets/flags_svg/us.svg",
"country_flag_emoji": "",
"country_flag_emoji_unicode": "U+1F1FA U+1F1F8",
"calling_code": "1",
"is_eu": false
},
"time_zone": {
"id": "America/Los_Angeles",
"current_time": "2018-03-29T07:35:08-07:00",
"gmt_offset": -25200,
"code": "PDT",
"is_daylight_saving": true
},
"currency": {
"code": "USD",
"name": "US Dollar",
"plural": "US dollars",
"symbol": "$",
"symbol_native": "$"
},
"connection": {
"asn": 25876,
"isp": "Los Angeles Department of Water & Power"
},
"security": {
"is_proxy": false,
"proxy_type": null,
"is_crawler": false,
"crawler_name": null,
"crawler_type": null,
"is_tor": false,
"threat_level": "low",
"threat_types": null
}
}
获取客户端IP地址,并使用任何IP到地理位置映射服务找到IP的位置。