11

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?

1
  • You don't want to create a new HttpClient for each request. Create it as a Singleton, use DefaultRequestHeaders for headers that are common to all requests, then set request-specific headers on an HttpRequestMessage and pass that into the HttpClient.SendAsync() method. Commented Apr 13, 2021 at 17:40

1 Answer 1

30

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

client.DefaultRequestHeaders.Add("api-key", "11111111");
Sign up to request clarification or add additional context in comments.

1 Comment

it needs to go to the header

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.