Introduction
Recently, a scenario arose in which we had to interact with 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 would be sharing this article for all those who wonder how! This is what my solution was to resolve this requirement. The implementation and the code is 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 Form and a web API project. So, the readers should know how to create a Windows Form and a web API 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. Let's have a look at the code:
private async void button1_Click(object sender, EventArgs e)
{
string value = "After Test Post API
(Result From API)";
var text = await DataReceivedHandler(value);
txtOutput.Text = text.Result;
}
private static async Task DataReceivedHandler(string value)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add
(new MediaTypeWithQualityHeaderValue("application/json"));
var url =
new Uri("http://localhost:54640/api/values?value=");
var result = await client.PostAsJsonAsync(url, value);
if (result.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return await Task.Delay(200)
.ContinueWith(t => "Hello");
}
string testResult = await result.Content.ReadAsStringAsync();
return testResult;
}
}
I am using async
method here, to post the values to the API and also awaiting 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, in case 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.
Conclusion
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 you have any suggestions or better implementation logic, I would love to learn.