在 C# 中使用带有 API 密钥的 HttpClient 类中的 PostAsync 方法

use*_*581 6 c# curl httprequest

我想用 C# 编写这个 curl 脚本的等价物。我的 curl 脚本如下:

curl -X POST \
https://example.com/login \
-H 'api-key: 11111111' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{
"username": "myemail@hotmail.com,
"password": "mypassword"
}'
Run Code Online (Sandbox Code Playgroud)

我编写的相应 C# 代码如下:

async static void PostRequest()
{
    string url="example.com/login"
    var formData = new List<KeyValuePair<string, string>>();
    formData.Add(new KeyValuePair<string, string>("username", "myemail@hotmail.com"));
    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();              
            }        
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在我的请求中包含 Api 密钥?

Ral*_*oss 17

对于您正在调用的 Api,密钥似乎在标题中。
所以使用:

client.DefaultRequestHeaders.Add("api-key", "11111111");
Run Code Online (Sandbox Code Playgroud)