We can Get and Post data from a Web API using Web client. Web client provides common methods for sending and receiving data from Server. Here, I have not used any authentication and authorization mechanism. This is simple - it's just for sending and receiving data from API.
First, you have to assign the API Endpoint on a variable. Here, I have created one static class to assign the API Endpoint.
- public static class StaticItems
- {
- public static string EndPoint = "http://localhost:8088/api/";
- }
Here, I have also created a class of name City.
- public class CityInfo
- {
- public int CityID { get; set; }
- public int CountryID { get; set; }
- public int StateID { get; set; }
- public string Name { get; set; }
- public decimal Latitude { get; set; }
- public decimal Longitude { get; set; }
- }
Receiving Data from API
This function retrieves data from API. Here, this function returns the list of cities. The data received from the API is in JSON format so I have deserialized that JSON data to an Object List. The Keyword DownloadString is used for retrieving data from Server.
- public List < CityInfo > CityGet() {
- try {
- using(WebClient webClient = new WebClient()) {
- webClient.BaseAddress = StaticItems.EndPoint;
- var json = webClient.DownloadString("City/CityGetForDDL");
- var list = JsonConvert.DeserializeObject < List < CityInfo >> (json);
- return list.ToList();
- }
- } catch (WebException ex) {
- throw ex;
- }
- }
Sending Data to Api
This function sends data to the API. Here, I have converted the object of the city into JSON.
The keyword UploadString is used for sending data to the Server.
- public ReturnMessageInfo CitySave(CityInfo city) {
- ReturnMessageInfo result = new ReturnMessageInfo();
- try {
- using(WebClient webClient = new WebClient()) {
- webClient.BaseAddress = StaticItems.EndPoint;
- var url = "City/CityAddUpdate";
- webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
- webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
- string data = JsonConvert.SerializeObject(city);
- var response = webClient.UploadString(url, data);
- result = JsonConvert.DeserializeObject < ReturnMessageInfo > (response);
- return result;
- }
- } catch (Exception ex) {
- throw ex;
- }
- }
Conclusion
Web client is easy to use for consuming the Web API. You can also use httpClient instead of WebClient. I hope you learned a little more about Web client and how a Web Client is used for sending and receiving data from Web API in C#. Let me know your queries in the comments section.