The HTTP Client is used to call the API in console application or any another .NET application, Here is the example to implement it.
Http request
GET: /api/Employees/
HttpClient
It is a class which is from System.Net.Http Namespace and provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
Complete Code:
- class Program
- {
- static void Main(string[] args)
- {
- Task T = new Task(ApiCall);
- T.Start();
- Console.WriteLine("Json data........");
- Console.ReadLine();
- }
- static async void ApiCall()
- {
-
- using (var client = new HttpClient())
- {
-
- HttpResponseMessage response = await client.GetAsync("http://localhost:57135/api/Employees/");
-
- response.EnsureSuccessStatusCode();
-
- using (HttpContent content = response.Content)
- {
- string responseBody = await response.Content.ReadAsStringAsync();
-
- Console.WriteLine(responseBody.Substring(0, 50) + "........");
-
- var articles = JsonConvert.DeserializeObject<List<Employee>>(responseBody);
-
-
-
- foreach (var Emp in articles)
- {
- Console.WriteLine("{0}\t{1}\t{2}\t{3}", Emp.EmployeeId, Emp.FirstName, Emp.LastName, Emp.Age);
- }
-
- }
-
- }
- }
Output:
I hope you enjoyed this blog. Your valuable feedback, question, or comments about this blog are always welcomed.