Fetch Web Api data to Console Application in C#

Fetch the Data from web ai to console screen.

Let's go-to application

In NuGet solution:- Install

PM> install-package Microsoft.AspNet.WebApi.Client



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ConsoleApp1
{

    public class Employee
    {
        public int id { get; set; }
        public int empid { get; set; }
        public string name { get; set; }
        public string address { get; set; }
        
    }
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://employees/list");
                //HTTP GET
                var responseTask = client.GetAsync("employees");
                responseTask.Wait();

                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {

                    var readTask = result.Content.ReadAsAsync<Employee[]>();
                    readTask.Wait();

                    var emps = readTask.Result;

                    foreach (var emp in emps)
                    {
                        Console.WriteLine(emp.empid + emp.name);
                    }
                }
            }
            Console.ReadLine();
           

        }
    }

}

output:-  1 xyz



Share this

Previous
Next Post »