The Forms And Web API Bridge


Recently, a scenario arose in which we had interact to a Web API from either a windows service or windows forms application. The logic and implementation seems easy once you are aware of the proceedings. I am sharing this article for all those who wonder how! This is what my solution was to resolve this requirement. The implementation and the code are simple, but only a copy/paste would not help unless we know what the keywords are and what they are meant for here. So let's see:


Get Started

Before I start, the basic requirement would be a windows forms and a web api project. So, the readers should know how to create a windows form and a WebAPI application as a prerequisite. I will be sharing the Windows Forms application, which will ping the API we set via the url. As we know the medium of interaction or the bridge is HttpClient.

According to MSDN

Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

As the above definition suggests, the HttpClient class helps send HTTP requests and also get back the responses from the API resource we have provided. (Not only API, this article focuses on API). Thus, HttpClient is our bridge here.
I have created a windows forms application, which will post some values to the API on click of a button and also get back the response from the API. Lets have a look at the code:

  1. private async void button1_Click(object sender, EventArgs e)  
  2.         {            
  3.             string value = "After Test Post API (Result From API)"//This value is sent to the API and again returned the same from it  
  4.             var text = await DataReceivedHandler(value);  
  5.             txtOutput.Text = text.Result;              
  6.         }  
  9.         private static async Task DataReceivedHandler(string value)  
  10.         {  
  11.               using (var client = new HttpClient())  
  12.             {  
  13.                 client.DefaultRequestHeaders.Accept.Clear();  
  14.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  15.                 var url = new Uri("http://localhost:54640/api/values?value="); //Change the Url to the Host (This is the default Values APi Controller)  
  16.                 var result = await client.PostAsJsonAsync(url, value);  
  17.                 if (result.StatusCode == System.Net.HttpStatusCode.NotFound)  
  18.                 {  
  19.                     return await Task.Delay(200)  
  20.                                 .ContinueWith(t => "Hello");  
  21.                 }  
  22.                 string testResult = await result.Content.ReadAsStringAsync();  
  23.                 return testResult;  
  24.             }  
  25.         }  

I am using async method here, to post the values to the API and also awaiting for the result/response from the API.

Snippet explanation

The default headers, the kind of media types we are sending may it be application/xml, application/xhtml+xml,or text/html. So for each request, we are clearing the headers and then annotating the media type we would be sending through the request.

Then, we are setting and formatting the url to the API, with the query string that needs to be passed.

Then we are posting to the API through the client object, using PostAsJsonAsyc. It is an async method which awaits internally for the response and gets back to the thread once the task is completed.

Then, we check for the response message status code, incase it is a failure (404/any other) or a success(200|OK).

If it is a success, through IsSuccessStatusCode (200|OK), then we are reading again asynchronously the string using ReadAsStringAsync() and finally returning the result from this method block.

This is actually the entire simple flow that flows through in the snippet and how we connect to the API using the bridge.


Here I have shown you how to post values to any API. This can be handy when you are using serial port values to be sent from any machine form client machine to your application hosted on other servers or even cloud. I hope this logic helps!

If any suggestion or better implementation logic, I would love to learn.

Read more articles on Windows Forms:

Similar Articles