Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass API key through HttpClient (C#)

On Postman I successfully posted a request with the followiong parameteres:

enter image description here

When I try to make the request with C# I get an unauthorized error maybe because I can’t pass the key value through the request.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s the code I’m using:

ClientAPI = new HttpClient();
ClientAPI.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", "api_token=00000000000000000000000000000000");

I already tried:

ClientAPI.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", "00000000000000000000000000000000");

or:

ClientAPI.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", "=00000000000000000000000000000000");

but I always get the unauthorized error. I think is because I’m sending this key on the Header but I noticed that, in Postman, the combo Add to is filled with Query Params. If I select Header in this combo I also get an unauthorized error on Postman.

Is this the reason? If so, how do I resolve the problem on C#?

>Solution :

Add you api_token to request params, not to headers

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https:yourequest_url?api_key=aval");
//if need
request.Headers.Add("Accept", "application/json");
....
//if need
var collection = new List<KeyValuePair<string, string>>();
collection.Add(new("p1", "v1"));
var content = new FormUrlEncodedContent(collection);
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading