You can use the code below to get the client IP address. that is, the IP address of the machine that requested the page on your website.
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(UserIP)) { UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; }
Below is the format to use for the API URL.
freegeoip.net/{format}/{IP_or_hostname}
Format
-> is the response output format. It can be CSV or XML or JSON.
For example, if we want to get a response in JSON format, we could use the API URL as http://freegeoip.net/json/clientIPAddress_here '
string url = "http://freegeoip.net/json/" + UserIP.ToString(); WebClient client = new WebClient(); string jsonstring = client.DownloadString(url);
To get a sample response, run http://freegeoip.net/json/XX.XX.XX.XX (replace XX.XX.XX.XX with the required ip address). right in the browser. You will see the following response format.
{ "ip":"xxx.xxx.xxx.xxx", "country_code":"", "country_name":"", "region_code":"", "region_name":"", "city":"", "zip_code":"", "time_zone":"", "latitude":0, "longitude":0, "metro_code":0 }
Use the code below to convert the response to a JSON object and then read the values of the JSON object and save it in a session variable or some other variable.
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); System.Web.HttpContext.Current.Session["LocId"] = dynObj.country_code;
You can also discover the country using the Location header. On HttpWebRequest you can set AllowAutoRedirect to false to handle the redirection yourself.
// don't allow redirects, they are allowed by default so we're going to override myRequest.AllowAutoRedirect = false; // send the request HttpWebResponse response = myRequest.GetResponse(); // check the header for a Location value if( response.Headers["Location"] == null ) { // null means no redirect } else { // anything non null means we got a redirect }
Solving the “Too many redirects” problem: The redirect cycle is similar to the situation where> “A points to B and B points to A” . Such redirection will support the browser in an infinite loop, and the web page will never be displayed. In the old days, such redirects or endless loops used to create a freezing browser. Currently, modern browsers are capable of detecting such redirection loops, and they break the loop causing the error message: "Error 310 (net :: ERR_TOO_MANY_REDIRECTS): there were too many redirects."
This problem can be caused either on the client side or on the server. If there is no redirect loop on the server side, the problem is likely to be solved only by deleting cookies from the browser.
Therefore, I suggest checking your routeeconfig.cs for such a route or a similar redirect operation that points to itself after deleting cookies from the browser
Hope this helps :)