在ASP.NET页面中查找客户端位置

3 c# asp.net geolocation

如何在我的ASP.NET页面中找到客户端位置?实际上我使用过System.Globalization.RegionInfo.CurrentRegion,但是它显示了控制面板中的设置.那么我可以使用任何方法找到确切的位置吗?

Sau*_*gin 5

并不是说它会给你100%的准确性,但你可以使用hostip.info

它们提供了一个API,为您提供通过HTTP请求传递的IP地址的位置.您可以使用WebClient对象来调用API并解析结果. Scott Hanselman这篇博客文章中有一个非常好的例子(下面我的例子基于他的文章).hostip.info的数据库基于一个开放式项目,社区将IP位置提供给......因此无法保证是正确的.

对于初学者,您需要确定客户端IP地址,如下所示:

string ipaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
Run Code Online (Sandbox Code Playgroud)

获得IP后,您可以创建WebClient对象并调用API ...

示例API调用:

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

结果将是XML,看起来像这样:

<?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>
Run Code Online (Sandbox Code Playgroud)