Вам не хватает преобразования типа во время шага добавления ... var x = y + z;
должно быть var x = parseInt(y) + parseInt(z);
<!DOCTYPE html>
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction()
{
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = parseInt(y) + parseInt(z);
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Это хороший образец для вас:
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 :)");
Я попытался использовать 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;
}
}
}
Использование запроса следующего веб-сайта
Ниже приведен код 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;
}
json
на xml
в адресе, чтобы получить структуру возврата XML.
– DonBoitnott
16 May 2018 в 10:57
Вам, вероятно, придется использовать внешний API, большая часть которого стоит денег.
Я нашел это, хотя, кажется, бесплатно: http://hostip.info/use .html
То, что вам нужно, называется «базой гео-IP». Большинство из них стоят денег (хотя и не слишком дорого), особенно довольно точных. Одним из наиболее широко используемых является база данных MaxMind . У них есть неплохая бесплатная версия базы данных IP-to-city, называемая GeoLity City - у нее много ограничений, но если вы справитесь с тем, что, вероятно, будет вашим лучшим выбором, если у вас нет деньги, необходимые для подписки на более точный продукт.
И, да, у них есть API C # для запроса баз данных гео-IP .
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"
// }
Вам нужен 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 класс I:
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; }
}
Я смог достичь этого в 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;
Вы можете пройти через этот пост для более подробной информации. Надеемся, что это поможет!
IPInfoDB имеет API , который вы можете вызвать, чтобы найти местоположение на основе IP-адреса.
Для «City Precision» вы называете это следующим образом (вы 'll нужно зарегистрировать, чтобы получить бесплатный ключ API):
http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false
Вот пример как в VB, так и в C #, который показывает, как вызвать API.
Альтернативой использованию API является использование навигатора местоположения HTML 5 для запроса браузера о местоположении пользователя. Я искал аналогичный подход, как в вопросе, но я обнаружил, что HTML 5 Navigator работает лучше и дешевле для моей ситуации. Пожалуйста, подумайте, что ваш сценарий может быть другим. Получить позицию пользователя с помощью 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
вы можете
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");
}