У мене є веб-сайт ASP.NET, написаний на C #.
На цьому веб-сайті мені потрібно автоматично показати стартову сторінку залежно від місцезнаходження користувача.
Чи можу я отримати назву міста користувача на основі IP-адреси користувача?
Відповіді:
Вам потрібен API зворотного геокодування на основі IP-адреси ... як той із ipdata.co . Я впевнений, що доступно безліч варіантів.
Однак ви можете дозволити користувачеві перевизначити це. Наприклад, вони можуть бути на корпоративній VPN , який робить IP - адреса зовнішній вигляд , як це в іншій країні.
Використовуйте http://ipinfo.io Вам потрібно заплатити їм, якщо ви робите більше 1000 запитів на день.
У наведеному нижче коді потрібен пакет Json.NET .
public static string GetUserCountryByIp(string ip)
{
IpInfo ipInfo = new IpInfo();
try
{
string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
ipInfo.Country = myRI1.EnglishName;
}
catch (Exception)
{
ipInfo.Country = null;
}
return ipInfo.Country;
}
І IpInfoклас, який я використовував:
public class IpInfo
{
[JsonProperty("ip")]
public string Ip { get; set; }
[JsonProperty("hostname")]
public string Hostname { get; set; }
[JsonProperty("city")]
public string City { get; set; }
[JsonProperty("region")]
public string Region { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("loc")]
public string Loc { get; set; }
[JsonProperty("org")]
public string Org { get; set; }
[JsonProperty("postal")]
public string Postal { get; set; }
}
Наступний код працює для мене.
Оновлення:
Оскільки я закликаю безкоштовний запит API (база json) IpStack .
public static string CityStateCountByIp(string IP)
{
//var url = "http://freegeoip.net/json/" + IP;
//var url = "http://freegeoip.net/json/" + IP;
string url = "http://api.ipstack.com/" + IP + "?access_key=[KEY]";
var request = System.Net.WebRequest.Create(url);
using (WebResponse wrs = request.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
var obj = JObject.Parse(json);
string City = (string)obj["city"];
string Country = (string)obj["region_name"];
string CountryCode = (string)obj["country_code"];
return (CountryCode + " - " + Country +"," + City);
}
return "";
}
Редагувати: По-перше, це було http://freegeoip.net/, зараз це https://ipstack.com/ (а, можливо, зараз це платна послуга - Безкоштовно до 10000 запитів на місяць)
jsonз xmlв адресі , щоб отримати зворотний XML структуру.
IPInfoDB має API, за яким ви можете зателефонувати, щоб знайти місце на основі IP-адреси.
Для "City Precision" ви називаєте це так (вам потрібно зареєструватися, щоб отримати безкоштовний ключ API):
http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false
Ось приклад як у VB, так і в C #, який показує, як викликати API.
Я спробував використовувати http://ipinfo.io, і цей JSON API працює ідеально. Спочатку потрібно додати згадані нижче простори імен:
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Specialized;
Для localhost він дасть фіктивні дані як AU. Ви можете спробувати кодувати свій IP і отримати результати:
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string VisitorsIPAddr = string.Empty;
//Users IP Address.
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
//To get the IP address of the machine and not the proxy
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;`enter code here`
}
string res = "http://ipinfo.io/" + VisitorsIPAddr + "/city";
string ipResponse = IPRequestHelper(res);
}
public string IPRequestHelper(string url)
{
string checkURL = url;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
string responseRead = responseStream.ReadToEnd();
responseRead = responseRead.Replace("\n", String.Empty);
responseStream.Close();
responseStream.Dispose();
return responseRead;
}
}
}
Я зміг досягти цього в ASP.NET MVC, використовуючи IP-адресу клієнта та freegeoip.net API . freegeoip.net є безкоштовним і не вимагає жодної ліцензії.
Нижче наведено зразок коду, який я використовував.
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;
Ви можете переглянути цю публікацію для отримання детальної інформації. Сподіваюся, це допоможе!
Використання запиту наступного веб-сайту
Далі наведено код C # для повернення країни та коду країни
public string GetCountryByIP(string ipAddress)
{
string strReturnVal;
string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress);
//return ipResponse;
XmlDocument ipInfoXML = new XmlDocument();
ipInfoXML.LoadXml(ipResponse);
XmlNodeList responseXML = ipInfoXML.GetElementsByTagName("query");
NameValueCollection dataXML = new NameValueCollection();
dataXML.Add(responseXML.Item(0).ChildNodes[2].InnerText, responseXML.Item(0).ChildNodes[2].Value);
strReturnVal = responseXML.Item(0).ChildNodes[1].InnerText.ToString(); // Contry
strReturnVal += "(" +
responseXML.Item(0).ChildNodes[2].InnerText.ToString() + ")"; // Contry Code
return strReturnVal;
}
А далі - помічник для запиту URL-адреси.
public string IPRequestHelper(string url) {
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
string responseRead = responseStream.ReadToEnd();
responseStream.Close();
responseStream.Dispose();
return responseRead;
}
Те, що вам потрібно, називається "база даних гео-IP". Більшість з них коштують певних грошей (хоча і не надто дорогих), особливо досить точних. Одним з найбільш широко використовуваних є база даних MaxMind . У них є досить хороша безкоштовна версія бази даних IP-to-city під назвою GeoLity City - вона має безліч обмежень, але якщо ви зможете впоратися з цим, це, мабуть, буде вашим найкращим вибором, якщо у вас немає грошей, які ви можете витратити на підписку на більш точний товар.
Так, у них є API C # для запиту доступних баз даних гео-IP .
Ймовірно, вам доведеться використовувати зовнішній API, більшість з яких коштує грошей.
Однак я знайшов це, здається, безкоштовно: http://hostip.info/use.html
static public string GetCountry()
{
return new WebClient().DownloadString("http://api.hostip.info/country.php");
}
Використання:
Console.WriteLine(GetCountry()); // will return short code for your country
static public string GetInfo()
{
return new WebClient().DownloadString("http://api.hostip.info/get_json.php");
}
Використання:
Console.WriteLine(GetInfo());
// Example:
// {
// "country_name":"COUNTRY NAME",
// "country_code":"COUNTRY CODE",
// "city":"City",
// "ip":"XX.XXX.XX.XXX"
// }
Це хороший зразок для вас:
public class IpProperties
{
public string Status { get; set; }
public string Country { get; set; }
public string CountryCode { get; set; }
public string Region { get; set; }
public string RegionName { get; set; }
public string City { get; set; }
public string Zip { get; set; }
public string Lat { get; set; }
public string Lon { get; set; }
public string TimeZone { get; set; }
public string ISP { get; set; }
public string ORG { get; set; }
public string AS { get; set; }
public string Query { get; set; }
}
public string IPRequestHelper(string url)
{
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
string responseRead = responseStream.ReadToEnd();
responseStream.Close();
responseStream.Dispose();
return responseRead;
}
public IpProperties GetCountryByIP(string ipAddress)
{
string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress);
using (TextReader sr = new StringReader(ipResponse))
{
using (System.Data.DataSet dataBase = new System.Data.DataSet())
{
IpProperties ipProperties = new IpProperties();
dataBase.ReadXml(sr);
ipProperties.Status = dataBase.Tables[0].Rows[0][0].ToString();
ipProperties.Country = dataBase.Tables[0].Rows[0][1].ToString();
ipProperties.CountryCode = dataBase.Tables[0].Rows[0][2].ToString();
ipProperties.Region = dataBase.Tables[0].Rows[0][3].ToString();
ipProperties.RegionName = dataBase.Tables[0].Rows[0][4].ToString();
ipProperties.City = dataBase.Tables[0].Rows[0][5].ToString();
ipProperties.Zip = dataBase.Tables[0].Rows[0][6].ToString();
ipProperties.Lat = dataBase.Tables[0].Rows[0][7].ToString();
ipProperties.Lon = dataBase.Tables[0].Rows[0][8].ToString();
ipProperties.TimeZone = dataBase.Tables[0].Rows[0][9].ToString();
ipProperties.ISP = dataBase.Tables[0].Rows[0][10].ToString();
ipProperties.ORG = dataBase.Tables[0].Rows[0][11].ToString();
ipProperties.AS = dataBase.Tables[0].Rows[0][12].ToString();
ipProperties.Query = dataBase.Tables[0].Rows[0][13].ToString();
return ipProperties;
}
}
}
І тест:
var ipResponse = GetCountryByIP("your ip address or domain name :)");
Альтернативою використанню API є використання навігатора розташування HTML 5 для запиту браузера про місцезнаходження Користувача. Я шукав подібний підхід, як у питанні, але виявив, що HTML 5 Navigator працює краще та дешевше для моєї ситуації. Будь ласка, врахуйте, що ваш scinario може бути іншим. Отримати позицію користувача за допомогою Html5 дуже просто:
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
console.log("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
console.log("Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude);
}
Спробуйте самі на підручнику з геолокації W3Schools
public static string GetLocationIPAPI(string ipaddress)
{
try
{
IPDataIPAPI ipInfo = new IPDataIPAPI();
string strResponse = new WebClient().DownloadString("http://ip-api.com/json/" + ipaddress);
if (strResponse == null || strResponse == "") return "";
ipInfo = JsonConvert.DeserializeObject<IPDataIPAPI>(strResponse);
if (ipInfo == null || ipInfo.status.ToLower().Trim() == "fail") return "";
else return ipInfo.city + "; " + ipInfo.regionName + "; " + ipInfo.country + "; " + ipInfo.countryCode;
}
catch (Exception)
{
return "";
}
}
public class IPDataIPINFO
{
public string ip { get; set; }
public string city { get; set; }
public string region { get; set; }
public string country { get; set; }
public string loc { get; set; }
public string postal { get; set; }
public int org { get; set; }
}
============================
public static string GetLocationIPINFO(string ipaddress)
{
try
{
IPDataIPINFO ipInfo = new IPDataIPINFO();
string strResponse = new WebClient().DownloadString("http://ipinfo.io/" + ipaddress);
if (strResponse == null || strResponse == "") return "";
ipInfo = JsonConvert.DeserializeObject<IPDataIPINFO>(strResponse);
if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
else return ipInfo.city + "; " + ipInfo.region + "; " + ipInfo.country + "; " + ipInfo.postal;
}
catch (Exception)
{
return "";
}
}
public class IPDataIPAPI
{
public string status { get; set; }
public string country { get; set; }
public string countryCode { get; set; }
public string region { get; set; }
public string regionName { get; set; }
public string city { get; set; }
public string zip { get; set; }
public string lat { get; set; }
public string lon { get; set; }
public string timezone { get; set; }
public string isp { get; set; }
public string org { get; set; }
public string @as { get; set; }
public string query { get; set; }
}
================================
private static string GetLocationIPSTACK(string ipaddress)
{
try
{
IPDataIPSTACK ipInfo = new IPDataIPSTACK();
string strResponse = new WebClient().DownloadString("http://api.ipstack.com/" + ipaddress + "?access_key=XX384X1XX028XX1X66XXX4X04XXXX98X");
if (strResponse == null || strResponse == "") return "";
ipInfo = JsonConvert.DeserializeObject<IPDataIPSTACK>(strResponse);
if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
else return ipInfo.city + "; " + ipInfo.region_name + "; " + ipInfo.country_name + "; " + ipInfo.zip;
}
catch (Exception)
{
return "";
}
}
public class IPDataIPSTACK
{
public string ip { get; set; }
public int city { get; set; }
public string region_code { get; set; }
public string region_name { get; set; }
public string country_code { get; set; }
public string country_name { get; set; }
public string zip { get; set; }
}
ти можеш
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
public ActionResult geoPlugin()
{
var url = "http://freegeoip.net/json/";
var request = System.Net.WebRequest.Create(url);
using (WebResponse wrs = request.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
var obj = JObject.Parse(json);
var City = (string)obj["city"];
// - For Country = (string)obj["region_name"];
//- For CountryCode = (string)obj["country_code"];
Session["CurrentRegionName"]= (string)obj["country_name"];
Session["CurrentRegion"] = (string)obj["country_code"];
}
return RedirectToAction("Index");
}
Rest Apiперевірте freegeoip.net або geoplugin.net , або перевірте цей і цей пост, сподіваюся, комусь допоможе.