How to Call and Consume Web API in Winform using C#

This post shows you How to call and read response from web api using c# code windows forms application.

We will use RestSharp to call web api from client. To play demo you need to install RestSharp from nuget packages or you can download it directly from https://github.com/restsharp/RestSharp

var client = new RestClient("https://localhost:44355/api/Account/");
var request = new RestRequest("Create", Method.POST);
LoginModel model = new LoginModel() { Username = "foxlearn", Password = "c-sharpcode.com" };
var json = JsonConvert.SerializeObject(model);
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);

IRestResponse contains all of the information returned from the remote server. You have access to the headers, content, HTTP status and more.

Note: If there is a network transport error the RestResponse.ResponseStatus will be set to Error, otherwise it will be Completed. If your API returns to 404, the ResponseStatus will still be Completed. If you need access to the HTTP status code returned you'll find it at RestResponse.StatusCode.

You can do as same as for HttpGetHttpPut and HttpDelete.

string _url = "https://localhost:44355";
string _token = "Put your token here";
var client = new RestClient(string.Format("{0}/api/Invoice/", _url));
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", _token));
var request = new RestRequest(string.Format("delete/{0}", id), Method.DELETE);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
JToken data = JToken.Parse(response.Content);

You can use JToken to parse content response from web api. To call the Web API using JWT (Json Web Token) authorization you need to add Authorization to header as shown below.

client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", _token));

You can use RestSharp to download data, then save data as file to your hard disk

var client = new RestClient(string.Format("{0}/api/Invoice/", _url));
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", _token));
var request = new RestRequest(string.Format("pdf/{0}", id), Method.GET);
request.RequestFormat = DataFormat.Json;
byte[] res = client.DownloadData(request);

You can write data with pdf format to file base on data that you get from web api

File.WriteAllBytes(Path.Combine(Application.StartupPath, string.Format("{0}.pdf", id)), res);