Introduction
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:
I am using async method here, to post the values to the API and also awaiting for the result/response from the API.
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 any suggestion or better implementation logic, I would love to learn.