繁体   English   中英

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

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

我想用 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"
}'

我编写的相应 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();              
            }        
        }
    }
}

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

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

client.DefaultRequestHeaders.Add("api-key", "11111111");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM