How to get visitor location ( country, state and city ) using ASP.NET

 ̄綄美尐妖づ 提交于 2019-11-28 03:52:10
Michael B.

Here how it is done in asp.net

Request.ServerVariables("REMOTE_ADDR")

Get a copy of IP adress database by location here

http://www.maxmind.com/

Shoban

Why not use Google Analytics? You will get more than what you need. Alternatively you can get the client's ip and use service like ip2location to get the location.

Check this similar question as well. finding clients location in asp.net page.

There are a few free web services out there which provide IP-to-location services. For instance:

http://freegeoip.net/
http://www.hostip.info/
http://ipinfodb.com/ip_location_api.php

anishMarokey

by using

string userHost = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(userHost) || 
    String.Compare(userHost, "unknown", true) == 0)
{
    userHost = Request.UserHostAddress;
}

you will get users ip address . Based on this ip address you can find out visitor location details by calling some webservice .

IPAddressExtensions is a free codeplex class library if all you just want is the Country the IP is located from.

First, get the IP address of the visitor using Request.ServerVariables("REMOTE_ADDR"). Bear in mind that the visitor could be using a proxy server in which case the IP address may not be their actual IP address. For the proxy case, you can check if Request.ServerVariables("HTTP_X_FORWARDED_FOR") contains a value. This will be the actual IP address if the proxy server is not an anonymous proxy server.

Then you have 2 options, using a web service or querying data from your own database. Either way, you will need data which can match an IP address of the visitor to their country, state and city.

Get the client IP and find the location of IP using any IP to geo location Mapping service.

This is what I've used:

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            'url': 'http://www.freegeoip.net/json/@(HttpContext.Current.Request.UserHostAddress)',
            'type': 'GET',
            'success': function(data) {
                // for example
                if (data.country_code === "GB") {
                    ... further logic here
                }
            }
        });
    });
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!