Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

c# - Finding clients location in an ASP.NET page

How to find clients location in my ASP.NET page? In fact I used System.Globalization.RegionInfo.CurrentRegion, but it is showing the setting in the control panel. So can I find the exact location using any method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not that it would give you 100% accuracy, but you can use hostip.info

They provide an API that gives you the location of an IP address that you pass them via HTTP request. You can use a WebClient object to make calls to the API and parse the results. Scott Hanselman has a pretty great example in this blog article (my example below is based on his article). hostip.info's database is based on an open project that the community contributes IP locations to... so there is no guarantee to be correct.

For starters, you need to determine the client IP address as follows:

string ipaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

Once you have the IP, you can create a WebClient object and call the API...

Example API call:

string r;
using (var w = new WebClient())
{
    r = w.DownloadString(String.Format("http://api.hostip.info/?ip={0}&position=true", ipaddress));
}

The results will be XML that looks something like this:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<HostipLookupResultSet version="1.0.0" xmlns="http://www.hostip.info/api" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.hostip.info/api/hostip-1.0.0.xsd">
 <gml:description>This is the Hostip Lookup Service</gml:description>
 <gml:name>hostip</gml:name>
 <gml:boundedBy>
    <gml:Null>inapplicable</gml:Null>
 </gml:boundedBy>
 <gml:featureMember>
    <Hostip>
     <gml:name>Sugar Grove, IL</gml:name>
     <countryName>UNITED STATES</countryName>
     <countryAbbrev>US</countryAbbrev>
     <!-- Co-ordinates are available as lng,lat -->
     <ipLocation>
        <gml:PointProperty>
         <gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
            <gml:coordinates>-88.4588,41.7696</gml:coordinates>
         </gml:Point>
        </gml:PointProperty>
     </ipLocation>
    </Hostip>
 </gml:featureMember>
</HostipLookupResultSet>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...