Get Offset Time using WebClient class

In this blog, I will explain the use of the WebClient class to get the Offset Time for .Net 2.0/3.0/4.0. 
Create 2 classes,

public class DataCapEntities

{
public double OffsetTime { get; set; }
}
And

public class User{

public User()

{

//

// TODO: Add constructor logic here

//

}

public string timeZone

{

get;

set;

}

} 
 
Create a method to get the User IP Address.

private static string GetUserIP()

{

string ipList = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (!string.IsNullOrEmpty(ipList))

{

return ipList.Split(',')[0];

}

return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

}

Call the above method to get the User IP Address. 

var clientIp = GetUserIP();

DataCapEntities objDataCapture = new DataCapEntities ();

Create object of WebClient class. 

WebClient client = new WebClient();

var url = "http://api.ipinfodb.com/v3/ip-city/?key= " + ConfigurationManager.AppSettings["GeoLocationKey"] + "&ip=" + clientIp + "&&format=json";

var response = client.DownloadString(new Uri(url));

if (response != "")

{

var j = Newtonsoft.Json.JsonConvert.DeserializeObject<User>(response);

objDataCapture.OffsetTime = (TimeSpan.Parse(j.timeZone.Replace("+", "")).TotalMinutes/60);

}

Ebook Download
View all
Learn
View all