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?
HttpClientfor each request. Create it as a Singleton, useDefaultRequestHeadersfor headers that are common to all requests, then set request-specific headers on anHttpRequestMessageand pass that into theHttpClient.SendAsync()method.