Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PostAsync method from HttpClient Class with an API key in C#

I would like to write the equivalent of this curl script in C#. My curl script is the following:

curl -X POST \
https://example.com/login \
-H 'api-key: 11111111' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{
"username": "[email protected],
"password": "mypassword"
}'

The corresponding C# code I have wrote is the following:

async static void PostRequest()
{
    string url="example.com/login"
    var formData = new List<KeyValuePair<string, string>>();
    formData.Add(new KeyValuePair<string, string>("username", "[email protected]"));
    formData.Add(new KeyValuePair<string, string>("password", "mypassword"));
    HttpContent q = new FormUrlEncodedContent(formData);
    // where do I put my api key?
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
        client.BaseAddress = new Uri(url);
        using (HttpResponseMessage response = await client.PostAsync(url, q))
        {
            using (HttpContent content =response.Content)
            {
                string mycontent = await content.ReadAsStringAsync();              
            }        
        }
    }
}

My question is how do I include the Api Key to my request?

like image 348
user3841581 Avatar asked Oct 14 '17 15:10

user3841581


1 Answers

For the Api you are calling, it appears as though the key is in the headers.
So use:

client.DefaultRequestHeaders.Add("api-key", "11111111");
like image 59
Ralph Willgoss Avatar answered Sep 22 '22 07:09

Ralph Willgoss