Sunday, 9 July 2017

, , ,

How to call web API from another web API using HttpClient?



Yes, it is a very short topic just like a question on any form. but I feel that many time we require to call web API from another project and sometimes it takes more time for such a small thing. So, I would like to share the easiest way of calling web API from another web API.


Please find the below code,


using (var client = new HttpClient())
           {
               client.BaseAddress = new Uri("http://localhost:portNumber");
               client.DefaultRequestHeaders.Accept.Clear();
               client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

               // If you need to add token with request,
               // uncomment the below code and replace 'token_value' with actual Token.
               // client.DefaultRequestHeaders.Add("Authorization", "Bearer " + "token_value");

               var response = client.GetAsync("route").Result;
               if (response.IsSuccessStatusCode)
               {
                   string responseString = response.Content.ReadAsStringAsync().Result;
               }
           }


Copy and paste above code in your service call and replace the 'portNumber' with your application port number if you are on localhost else replace the whole URL with your actual URL. The second thing to replace is 'route', change it with you api route like 'api/value/10'. Now all is yours, enjoy.

This thing will help you in calling microservices and creating the api end-end testing project.


I hope you will like it and feel free to comment or reaching me if you have any doubt.

Share:

0 comments:

Post a Comment