Call and consume Web API in winform using C#.net

Just use the following library.

https://www.nuget.org/packages/RestSharp

GitHub Project: https://github.com/restsharp/RestSharp

Sample Code::

    public Customer GetCustomerDetailsByCustomerId(int id)
    {
        var client = new RestClient("http://localhost:3000/Api/GetCustomerDetailsByCustomerId/" + id);
        var request = new RestRequest(Method.GET);
        request.AddHeader("X-Token-Key", "dsds-sdsdsds-swrwerfd-dfdfd");
        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string
        dynamic json = JsonConvert.DeserializeObject(content);
        JObject customerObjJson = json.CustomerObj;
        var customerObj = customerObjJson.ToObject<Customer>();
        return customerObj;
    }

You can take a look at the following docs tutorial:

  • Call a Web API From a .NET Client

But as an answer, here I will share a quick and short a step by step guide about how to call and consume web API in Windows forms:

  1. Install Package - Install the Microsoft.AspNet.WebApi.Client NuGet package (Web API Client Libraries).

    Open Tools menu → NuGet Package Manager → Package Manager Console → In the Package Manager Console window, type the following command:

     Install-Package Microsoft.AspNet.WebApi.Client
    

    You can install package by right click on project and choosing Manage NuGet Packages as well.

  2. Set up HttpClient - Create an instance of HttpClient and set up its BaseAddress and DefaultRequestHeaders. For example:

     // In the class
     static HttpClient client = new HttpClient();
    
     // Put the following code where you want to initialize the class
     // It can be the static constructor or a one-time initializer
     client.BaseAddress = new Uri("http://localhost:4354/api/");
     client.DefaultRequestHeaders.Accept.Clear();
     client.DefaultRequestHeaders.Accept.Add(
         new MediaTypeWithQualityHeaderValue("application/json"));
    
  3. Send Request - To send the requests, you can use the following methods of the HttpClient:

    • GET: GetAsync, GetStringAsync, GetByteArrayAsync, GetStreamAsync
    • POST: PostAsync, PostAsJsonAsync, PostAsXmlAsync
    • PUT: PutAsync, PutAsJsonAsync, PutAsXmlAsync
    • DELETE: DeleteAsync
    • Another HTTP method: Send

    Note: To set the URL of the request for the methods, keep in mind, since you have specified the base URL when you defined the client, then here for these methods, just pass path, route values and query strings, for example:

     // Assuming http://localhost:4354/api/ as BaseAddress 
     var response = await client.GetAsync("products");
    

    or

     // Assuming http://localhost:4354/api/ as BaseAddress 
     var product = new Product() { Name = "P1", Price = 100, Category = "C1" };
     var response = await client.PostAsJsonAsync("products", product);
    
  4. Get the Response

    To get the response, if you have used methods like GetStringAsync, then you have the response as string and it's enough to parse the response. If the response is a Json content which you know, you can easily use JsonConvert class of Newtonsoft.Json package to parse it. For example:

     // Assuming http://localhost:4354/api/ as BaseAddress 
     var response = await client.GetStringAsync("product");
     var data = JsonConvert.DeserializeObject<List<Product>>(response);
     this.productBindingSource.DataSource = data; 
    

    If you have used methods like GetAsync or PostAsJsonAsync and you have an HttpResponseMessage then you can use ReadAsAsync, ReadAsByteArrayAsync, ReadAsStreamAsync, `ReadAsStringAsync, for example:

     // Assuming http://localhost:4354/api/ as BaseAddress 
     var response = await client.GetAsync("products");
     var data = await response.Content.ReadAsAsync<IEnumerable<Product>>();
     this.productBindingSource.DataSource = data;
    

Performance Tip

  • HttpClient is a type that is meant to be created once and then shared. So don't try to put it in a using block every time that you want to use it. Instead, create an instance of the class and share it through a static member. To read more about this, take a look at Improper Instantiation antipattern

Design Tip

  • Try to avoid mixing the Web API related code with your application logic. For example let's say you have a product Web API service. Then to use it, first define an IProductServieClient interface, then as an implementation put all the WEB API logic inside the ProductWebAPIClientService which you implement to contain codes to interact with WEB API. Your application should rely on IProductServieClient. (SOLID Principles, Dependency Inversion).