Search code examples
c#httpclientunauthorized

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.

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());