0

I have given below the sample code, I am calling web API but I am struggling to pass the parameter in the console application.

C# code:

HttpClient client = new HttpClient(); var responseTask = client.GetAsync("<web api name>"); responseTask.Wait(); HttpRequestMessage rm = new HttpRequestMessage(); var headers = rm.Headers; client.DefaultRequestHeaders.Add("client_id", "1234xv"); client.DefaultRequestHeaders.Add("client_secret", "7dfdfsd"); if (responseTask.IsCompleted) { var result = responseTask.Result; if (result.IsSuccessStatusCode) { var messageTask = result.Content.ReadAsStringAsync(); messageTask.Wait(); Console.WriteLine("Message from Web API:" + messageTask.Result); Console.ReadLine(); } } 
3
  • try using (var httpClient = new HttpClient()) Commented Dec 30, 2021 at 12:12
  • You should be using await for the async calls instead of .Result or Wait() Commented Dec 30, 2021 at 12:16
  • You are making the GET call too early, before adding parameters to the HTTP request headers. Is the web API expecting the params in headers or query string or body ? Commented Dec 30, 2021 at 12:22

1 Answer 1

1

You were making the GET call much early, even before adding the parameters to the HTTP headers. You need to add the params and then call the GetAsync(). See the modified code below,

using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("client_id", "1234xv"); client.DefaultRequestHeaders.Add("client_secret", "7dfdfsd"); var responseTask = client.GetAsync("http://your api url"); responseTask.Wait(); if (responseTask.IsCompleted) { var result = responseTask.Result; if (result.IsSuccessStatusCode) { var messageTask = result.Content.ReadAsStringAsync(); messageTask.Wait(); Console.WriteLine("Message from Web API:" + messageTask.Result); Console.ReadLine(); } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! @Anand Sowmithiran

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.