Error in reading json API - c#

I am trying to fetch a list of products by accessing the API prodvided by the store. Following is my code
public class CKProductAPI
{
public List<ProductListNames> ProductList(string url)
{
List<ProductListNames> objProducts = new List<ProductListNames>();
try
{
var wc = new WebClient();
wc.Headers.Add("Fk-Affiliate-Id", ConfigurationManager.AppSettings["FK-AFFID"]);
wc.Headers.Add("Fk-Affiliate-Token", ConfigurationManager.AppSettings["FK-TKN"]);
string productFeedXml = wc.DownloadString(url);
JObject jObject = (JObject)JsonConvert.DeserializeObject(productFeedXml);
var jProductData = jObject["productInfoList"];
foreach (var item in jProductData)
{
string strproductId, strtitle, strimageUrls, strmaximumRetailPrice, strsellingPrice, strcurrency, strproductBrand, strproductUrl, strinStock;
try { strproductId = item["productBaseInfo"]["productIdentifier"]["productId"].ToString(); }
catch { strproductId = ""; }
try { strtitle = item["productBaseInfo"]["productAttributes"]["title"].ToString(); }
catch { strtitle = ""; }
try { strimageUrls = item["productBaseInfo"]["productAttributes"]["imageUrls"].ToString(); }
catch { strimageUrls = ""; }
try { strmaximumRetailPrice = item["productBaseInfo"]["productAttributes"]["maximumRetailPrice"].ToString(); }
catch { strmaximumRetailPrice = ""; }
try { strsellingPrice = item["productBaseInfo"]["productAttributes"]["sellingPrice"].ToString(); }
catch { strsellingPrice = ""; }
try { strcurrency = item["productBaseInfo"]["productAttributes"]["currency"].ToString(); }
catch { strcurrency = ""; }
try { strproductBrand = item["productBaseInfo"]["productAttributes"]["productBrand"].ToString(); }
catch { strproductBrand = ""; }
try { strproductUrl = item["productBaseInfo"]["productAttributes"]["productUrl"].ToString(); }
catch { strproductUrl = ""; }
try { strinStock = item["productBaseInfo"]["productAttributes"]["inStock"].ToString(); }
catch { strinStock = ""; }
objProducts.Add(new ProductListNames
{
productId = strproductId,
title = strtitle,
imageUrls = strimageUrls,
maximumRetailPrice = strmaximumRetailPrice,
sellingPrice = strsellingPrice,
currency = strcurrency,
productBrand = strproductBrand,
productUrl = strproductUrl,
inStock = strinStock
});
}
}
catch (Exception)
{
throw;
}
return objProducts;
}
public class ProductListNames
{
public string productId { get; set; }
public string title { get; set; }
public string imageUrls { get; set; }
public string maximumRetailPrice { get; set; }
public string sellingPrice { get; set; }
public string currency { get; set; }
public string productUrl { get; set; }
public string productBrand { get; set; }
public string inStock { get; set; }
public string size { get; set; }
}
}
I am getting the following error ::
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

It seems you are getting xml response.
If adding ACCEPT header doesn't help (as refgor said) then you might need to serialize xml to json first then use it as JObject. This might help.
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
SO Post
You can then parse jsonText using JObject.Parse(jsonText)

It seems to be your source JSON string is invalid or is not actually a JSON string.
Please check HTTP request you are making, whether server delivers you JSON. HTTP service might respond differently based on Accept header you are adding to your HTTP request.
To make sure you are asking service about JSON, you can add Accept: application/JSON HTTP header to your request. Otherwise, server might decide by itself and respond with XML on your request.
If your server responds with JSON then it might help:
var wc = new WebClient();
client.Headers.Set("Accept", "application/json");
You can also check Content-Type of your response but then you need to use another method of WebClient, not a DownloadString

Related

Restsharp Doesn't Deserialize Enumeration

I'm trying to call an external RESTful API in my application and I've been using restsharp for it which has been great so far so but I think I've ran into a problem.
I'm calling an API which normally returns XML documents like this:
<res>
<resultCode>100</resultCode>
<resultText>OK</resultText>
<messageId>52788198</messageId>
<sessionId>TEST</sessionId>
<operatorCode>22802</operatorCode>
</res>
This is my code:
internal class SubmitMessageResponse
{
public ResultCode resultCode { get; set; }
public string resultText { get; set; }
public string messageId; { get; set; }
public string sessionId; { get; set; }
public string operatorCode; { get; set; }
}
public SubmitMessageResponse SendWelcomeSMS(string subscriptionId, string msisdn)
{
var request = new RestRequest(Method.GET);
request.AddQueryParameter("command", "submitMessage")
.AddQueryParameter("username", _Config.User)
.AddQueryParameter("password", _Config.Password)
.AddQueryParameter("msisdn", "00" + _Club.CountryCode + msisdn)
.AddQueryParameter("businessNumber", _Club.SubscribeShortCode)
.AddQueryParameter("content", _Club.WelcomeMessage)
.AddQueryParameter("price", "0")
.AddQueryParameter("sessionId", subscriptionId)
.AddQueryParameter("label", "W")
.AddQueryParameter("keyword", _Club.SubscribeKeyword)
.AddQueryParameter("operatorCode", "test");
return SendGetRequest<SubmitMessageResponse>(request);
}
private T SendGetRequest<T>(RestRequest request) where T : new()
{
try
{
var client = new RestClient(this._BaseUrl);
client.Timeout = 10000;
_Logger.DebugFormat("{0} Request: {1}", "submitMessage", client.BuildUri(request));
var data = client.Execute<T>(request);
_Logger.DebugFormat("{0} Response: {1}", "submitMessage", Newtonsoft.Json.JsonConvert.SerializeObject(data.Content));
return data.Data;
} catch(Exception e)
{
_Logger.Error(e);
}
return default(T);
}
Where ResultCode is an enumeration including all known values that this API returns:
internal enum ResultCode
{
Ok = 100,
AuthorizationInProgress = 150,
PaymentAuthInProcess = 150,
InvalidOperatorCode = 201,
...
}
The problem is that normally this would work correctly but I'm unable to deserialize the enum from the XML:
var response = apiHelper.SendWelcomeSMS(client.ExternalData, client.Number);
Logger.Debug(Newtonsoft.Json.JsonConvert.SerializeObject(response));
My log:
{"messageId":"52788292","sessionId":"TEST","operatorCode":"22802","**resultCode**":0,"resultText":"OK"}
But I also log the response and it works fine:
submitMessage Response: "<res>\r\n\t<**resultCode**>**100**</**resultCode**>\r\n\t<resultText>OK</resultText>\r\n\t<messageId>52788292</messageId>\r\n\t<sessionId>TEST</sessionId>\r\n\t<operatorCode>22802</operatorCode>\r\n</res>\r\n"
Any advice is appreciated.

How to Parse Json from UrI to list on Xamarin Android

I tried too many but no success
this is my method to get JSON string from web service Uri and deserialize it to list, and I want to use it on Xamarin Android App
public async void DownloadDataAsync()
{
string url = "http://myWebSite.com/jWebService.asmx/GetOffersJSON?storeID=2";
var httpClient = new HttpClient();
Task <string> downloadTask = httpClient.GetStringAsync(url);
string content = await downloadTask;
// de-serializing json response into list
JObject jsonResponse = JObject.Parse(content);
IList<JToken> results = jsonResponse["offs"].ToList();
foreach (JToken token in results)
{
offers poi = JsonConvert.DeserializeObject<offers>(token.ToString());
offs.Add(poi);
}
}
when I call DownloadDataAsync(); I get an error:
An unhandled exception occured.
what is the solution?
I've parameter on my web service method, who can I deal with it?
Here is my JSON Uri result:
This XML file does not appear to have any style information associated with
it. The document tree is shown below.
<string xmlns="http://tempuri.org/">[{"ItemID":20,"ItemBarcode":"111","ItemName":"hgh","ItemImage":"MegaOrders22017-04-14-08-34-27.jpg","ItemPrice":7.0000,"ItemNotes":"gffgdfj","OfferOn":true},{"ItemID":21,"ItemBarcode":"222","ItemName":"Nod","ItemImage":"MegaOrders22017-04-14-08-34-57.jpg","ItemPrice":4.0000,"ItemNotes":"kkkkkk","OfferOn":true},{"ItemID":22,"ItemBarcode":"333","ItemName":"kjkjkjkj","ItemImage":"MegaOrders22017-04-14-08-35-21.jpg","ItemPrice":6.0000,"ItemNotes":"hhhhggggg","OfferOn":true},{"ItemID":23,"ItemBarcode":"4444","ItemName":"oioioio","ItemImage":"MegaOrders22017-04-14-08-35-50.jpg","ItemPrice":5.0000,"ItemNotes":"hjhgfdfghj","OfferOn":true}]
</string>
the Class I used:
public class offers
{
public int ItemID { get; set; }
public string ItemBarcode { get; set; }
public string ItemName { get; set; }
public string ItemImage { get; set; }
public double ItemPrice { get; set; }
public string ItemNotes { get; set; }
public bool OfferOn { get; set; }
}
Please try this:
public async void DownloadDataAsync()
{
try
{
string url = "http://myWebSite.com/jWebService.asmx/GetOffersJSON?storeID=2";
var httpClient = new HttpClient();
var content = await httpClient.GetStringAsync(url);
// de-serializing json response into list, with filtering before
var startPosition = content.IndexOf('>') + 1;
var endPosition = content.LastIndexOf("</", StringComparison.Ordinal);
var filteredResponseCharArray = new char[endPosition - startPosition];
content.CopyTo(startPosition, filteredResponseCharArray, 0, endPosition - startPosition);
var listOfOffers = JsonConvert.DeserializeObject<List<offers>>(new string(filteredResponseCharArray));
}
catch (Exception error)
{
Debug.WriteLine(error);
throw;
}
}
You should change your web service to get a valid JSON response without XML structure.

Show json error tag in C#

I have a json in an Api with an error tag. Now I want to show the error content in c# when an error occurs. Does anyone have a code or an example for this?
--Edited--
string html = string.Empty;
string url = #"http://henn.worteus.eu/?tag=getdatas&token=21123&id=" + sessions;
WebRequest req = WebRequest.Create(url);
req.ContentType = "application/json";
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader re = new StreamReader(stream);
string json = re.ReadToEnd();
// Wrapper w = (Wrapper)new JavaScriptSerializer().Deserialize(json, typeof(Wrapper));
Wrapper w = (Wrapper)JsonConvert.DeserializeObject(json, typeof(Wrapper));
dataGrid.ItemsSource = w.data;
Here are the data models
public class Data
{
public string Skala { get; set; }
public string Wert { get; set; }
public string Bereich { get; set; }
public string Interpretationen { get; set; }
}
public class Wrapper
{
public List<Data> data { get; set; }
public string tag { get; set; }
public object error { get; set; }
}
If there is an error property on the returned model
{
"error":"...",
"data":[...]
}
then desrialize the json to a strong type and then access the property
Wrapper w = JsonConvert.DeserializeObject<Wrapper>(json);
var data = w.data;
var error = w.error;
if(error != null) {
//...perform some action
}

How to read the contents of a json post with asp before processing the request?

What I want to do is extremely simple in php. I just want to read the contents of the post. It also extremely simple on sailsjs / node ... I just return the result from within the async function.
In c# asp the answer is eluding me. I want the function to read the contents of the post before it attempts to process the post.
Sometimes the following code works. Sometimes the reading of the json from the post happens too slowly and jsonText is read as "" so nothing is processed.
In all of the test runs the json is being sent in the body of the post.
What is the best way to return a httpResponse after making sure the contents of the post is read first?
public HttpResponseMessage Post()
{
string content;
try
{
string result = String.Empty;
Newtonsoft.Json.Linq.JObject jObject = null;
string jsonText = String.Empty;
var syncTask = new Task<string>( () => {
return Request.Content.ReadAsStringAsync().Result;
});
/* I'm expecting that this will finish */
syncTask.RunSynchronously();
jsonText = syncTask.Result;
/* before this line of code executes */
System.Net.Http.HttpResponseMessage response = new HttpResponseMessage();
if (jsonText == "")
{
result = "{\"error\":\"body is empty\"}";
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
}
else
{
jObject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JRaw.Parse(jsonText);
string ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
jObject["ipAddress"] = ipAddress;
Models.JsonXML jsonXml = new JsonXML(jObject.ToString(Newtonsoft.Json.Formatting.None));
System.Xml.XmlDocument document = new System.Xml.XmlDocument();
document.LoadXml(jsonXml.xml);
result = ReferralsManager.ProcessReferral(document);
if (result == "")
{
result = "{}";
}
response.StatusCode = System.Net.HttpStatusCode.OK;
}
response.Content = new StringContent(result);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
return response;
}
catch (Exception ex)
{
content = ErrorMessage.ServerException(Converter, ex);
return Request.ToResponseMessage(content);
}
finally
{
LogManager.GetCurrentClassLogger().Info(InfoMessage.FUNC_ENDS, "Process Referral");
}
}
The working modified code after the answer from #Mekap is
public class ProcessReferralAddressModel {
public ProcessReferralAddressModel() { }
public string address { get; set; }
public string name { get; set; }
}
public class ProcessReferralModel
{
public ProcessReferralModel()
{
}
public string uuid { get; set; }
public DateTime date { get; set; }
public ProcessReferralAddressModel from { get; set; }
public ProcessReferralAddressModel[] to { get; set; }
public string subject { get; set; }
public string text { get; set; }
public string html { get; set; }
}
/// <summary>
/// Process a referral.
/// </summary>
/// <param name="userid">The userid.</param>
/// <returns></returns>
public HttpResponseMessage Post([FromBody] ProcessReferralModel processReferralModel)
{
string content;
string jsonText = Newtonsoft.Json.JsonConvert.SerializeObject(processReferralModel) ;
try
{
string result = String.Empty;
Newtonsoft.Json.Linq.JObject jObject = null;
System.Net.Http.HttpResponseMessage response = new HttpResponseMessage();
if (jsonText == "" || jsonText == null )
{
result = "{\"error\":\"body is empty\"}";
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
}
else
{
jObject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JRaw.Parse(jsonText);
string ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
jObject["ipAddress"] = ipAddress;
Models.JsonXML jsonXml = new JsonXML(jObject.ToString(Newtonsoft.Json.Formatting.None));
System.Xml.XmlDocument document = new System.Xml.XmlDocument();
document.LoadXml(jsonXml.xml);
result = ReferralsManager.ProcessReferral(document);
if (result == "")
{
result = "{}";
}
response.StatusCode = System.Net.HttpStatusCode.OK;
}
response.Content = new StringContent(result);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
return response;
}
catch (Exception ex)
{
content = ErrorMessage.ServerException(Converter, ex);
return Request.ToResponseMessage(content);
}
finally
{
LogManager.GetCurrentClassLogger().Info(InfoMessage.FUNC_ENDS, "Process Referral");
}
}
The json you're fetching, for our example will look something like
{ "ID" : 3,
"StringCmd" : "ls -l"
}
For starters, we are going to write a small class who's representing our data in your web api
public class StringCmdModel
{
public StringCmdModel()
{
}
public int ID { get; set; }
public string StringCmd { get; set; }
}
Now, we just have to write our Entry point in our WebAPI :
[HttpPost]
public HttpResponseMessage PostFonction([FromBody] StringCmdModel NewEntry)
You don't have to check for the existence of the data inside the function. But you should still do proper checks on theirs values, in case you get bad formated json or malicious calls.
But, if you get a call with json that is not matching the StringCmdModel you gave in parameter from the body, this function will not be executed, and the server will throw on its own a 500 error.

Get user location by IP address [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 months ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have an ASP.NET website written in C#.
On this site I need to automatically show a start page based on the user's location.
Can I get name of user's city based on the IP address of the user ?
You need an IP-address-based reverse geocoding API... like the one from ipdata.co. I'm sure there are plenty of options available.
You may want to allow the user to override this, however. For example, they could be on a corporate VPN which makes the IP address look like it's in a different country.
Use http://ipinfo.io , You need to pay them if you make more than 1000 requests per day.
The code below requires the Json.NET package.
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;
}
And the IpInfo Class I used:
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; }
}
Following Code work for me.
Update:
As I am calling a free API request (json base ) 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 "";
}
Edit :
First, it was http://freegeoip.net/ now it's https://ipstack.com/ (and maybe now it's a paid service- Free Up to 10,000 request/month)
IPInfoDB has an API that you can call in order to find a location based on an IP address.
For "City Precision", you call it like this (you'll need to register to get a free API key):
http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false
Here's an example in both VB and C# that shows how to call the API.
I have tried using http://ipinfo.io and this JSON API works perfectly. First, you need to add the below mentioned namespaces:
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Specialized;
For localhost it will give dummy data as AU. You can try hardcoding your IP and get results:
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;
}
}
}
I was able to achieve this in ASP.NET MVC using the client IP address and freegeoip.net API. freegeoip.net is free and does not require any license.
Below is the sample code I used.
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;
You can go through this post for more details.Hope it helps!
Using the Request of following web site
http://ip-api.com/
Following is C# code for returning Country and Country Code
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;
}
And following is Helper for requesting 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;
}
What you need is called a "geo-IP database". Most of them cost some money (albeit not too expensive), especially fairly precise ones. One of the most widely used is MaxMind's database. They have a fairly good free version of IP-to-city database called GeoLity City - it has lots of restrictions, but if you can cope with that that would be probably your best choice, unless you have some money to spare for a subscription to more accurate product.
And, yeah, they do have a C# API to query geo-IP databases available.
You'll probably have to use an external API, most of which cost money.
I did find this though, seems to be free: http://hostip.info/use.html
Return country
static public string GetCountry()
{
return new WebClient().DownloadString("http://api.hostip.info/country.php");
}
Usage:
Console.WriteLine(GetCountry()); // will return short code for your country
Return info
static public string GetInfo()
{
return new WebClient().DownloadString("http://api.hostip.info/get_json.php");
}
Usage:
Console.WriteLine(GetInfo());
// Example:
// {
// "country_name":"COUNTRY NAME",
// "country_code":"COUNTRY CODE",
// "city":"City",
// "ip":"XX.XXX.XX.XXX"
// }
It's good sample for you:
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;
}
}
}
And test:
var ipResponse = GetCountryByIP("your ip address or domain name :)");
An Alternative to using an API is to use HTML 5 location Navigator to query the browser about the User location. I was looking for a similar approach as in the subject question but I found that HTML 5 Navigator works better and cheaper for my situation. Please consider that your scinario might be different.
To get the User position using Html5 is very easy:
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);
}
Try it yourself on W3Schools Geolocation Tutorial
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; }
}

Categories