Did you know there have different ways to consume a Web API in .NET? In this post, it will show different methods to call an API.

1) Using WebClient

  string GetApiByWebClient(string byQuery, string byHeader)  {      using WebClient webClient = new WebClient();      if (byHeader.Length > 0)      {          webClient.Headers.Add("name", byHeader);      }      webClient.Headers.Add("Accept", "application/json");      webClient.Headers.Add("Content-Type", "application/json");      return webClient.DownloadString(myApiUrl + (byQuery.Length == 0 ? "" : "?name=" + byQuery));  }    string PostApiByWebClient(string data)  {      using WebClient webClient = new WebClient();      webClient.Headers.Add("Accept", "application/json");      webClient.Headers.Add("Content-Type", "application/json");      return webClient.UploadString(myApiUrl, WebRequestMethods.Http.Post, data);  }  

2) Using HttpWebRequest

  string PostApiByHttpWebRequest(string data)  {      HttpWebRequest webClient = (HttpWebRequest)WebRequest.Create(myApiUrl);      webClient.Accept = "application/json"      webClient.ContentType = "application/json"      webClient.Method = WebRequestMethods.Http.Post;      webClient.ContentLength = data.Length;      using (var writer = new System.IO.StreamWriter(webClient.GetRequestStream()))      {          writer.Write(data);      }      var response = webClient.GetResponse() as HttpWebResponse;      using (var streamReader = new StreamReader(response.GetResponseStream()))      {          return streamReader.ReadToEnd();      }  }  

3) Using HttpClient

  async Task<string> PostApiByHttpClientAsync(string data)  {      string result = ""        using (var httpClient = new HttpClient())      {          httpClient.DefaultRequestHeaders.Add("Accept", "application/json");            HttpContent httpContent = new StringContent(data);          httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");            using (HttpResponseMessage response = await httpClient.PostAsync(myApiUrl, httpContent))          {              if (response.Content != null && response.IsSuccessStatusCode)              {                  result = await response.Content.ReadAsStringAsync();              }              else              {                  if (response.Content != null)                  {                      result = await response.Content.ReadAsStringAsync();                      string message = "POST Response Fail : " + result;                      throw new Exception(message);                  }                  else                  {                      string message = "POST Response Fail : No response"                      throw new Exception(message);                  }              }          }      }        return result;  }  

Apparently, the third method is longer, but as you can see from the code, it is an asynchronous method, which means it is an efficient approach towards activities blocked or access is delayed e.g. Web API. Therefore, it is a recommended method if responsive is important for the application you want to develop.

Bonus:
4) Using Powershell
Lastly, how about after you deployed to an environment and it is not working? You not sure is it due to a firewall or network issue and you have no tools like POSTMAN....? Then, PowerShell can come to help.

  PS D:\Temp\dotnetcore\ConsumeAPI> Invoke-WebRequest -Uri http://localhost:7071/api/HttpExample `  >>     -ContentType 'application/json' `  >>     -Method POST `  >>     -Body '{name: "POST API request from PowerShell"}'      StatusCode        : 200  StatusDescription : OK  Content           : Hello, POST API request from PowerShell.  RawContent        : HTTP/1.1 200 OK                      Transfer-Encoding: chunked                      Content-Type: text/plain; charset=utf-8                      Date: Sat, 14 Aug 2021 09:16:38 GMT                      Server: Kestrel                        Hello, POST API request from PowerShell.  Forms             : {}  Headers           : {[Transfer-Encoding, chunked], [Content-Type, text/plain; charset=utf-8], [Date, Sat, 14 Aug 2021                      09:16:38 GMT], [Server, Kestrel]}  Images            : {}  InputFields       : {}  Links             : {}  ParsedHtml        : mshtml.HTMLDocumentClass  RawContentLength  : 40  

This free site is ad-supported. Learn more