如何使用 System.Net.Http 发送如下所示的 cURL 请求?

How do I send the cURL request shown below using System.Net.Http?

我正在尝试使用 Zendesk 的票证提交 API,在他们的文档中,他们在 cURL 中给出了以下示例:

curl https://{subdomain}.zendesk.com/api/v2/tickets.json \ -d '{"ticket": {"requester": {"name": "The Customer", "email": "thecustomer@domain.com"}, "subject": "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}' \ -H "Content-Type: application/json" -v -u {email_address}:{password} -X POST

我正在尝试使用 System.Net.Http 库发出此 POST 请求:

var httpClient = new HttpClient();
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(model));
if (httpContent.Headers.Any(r => r.Key == "Content-Type"))
    httpContent.Headers.Remove("Content-Type");
httpContent.Headers.Add("Content-Type", "application/json");
httpContent.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes("{user}:{password}"))));
var httpResult = httpClient.PostAsync(WebConfigAppSettings.ZendeskTicket, httpContent);

当我尝试向内容添加授权 header 时,我总是收到错误消息。我现在明白 HttpContent 只应该包含内容类型 headers.

如何创建和发送 POST 请求,我可以在其中设置 Content-Type header、授权 header,并在其中包含 Json body 使用 System.Net.Http 库?

我使用下面的代码来构建我的请求:

HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(new { ticket = model }));
if (httpContent.Headers.Any(r => r.Key == "Content-Type"))
    httpContent.Headers.Remove("Content-Type");
httpContent.Headers.Add("Content-Type", "application/json");
var httpRequest = new HttpRequestMessage()
{
    RequestUri = new Uri(WebConfigAppSettings.ZendeskTicket),
    Method = HttpMethod.Post,
    Content = httpContent
};
httpRequest.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(@"{username}:{password}"))));
httpResult = httpClient.SendAsync(httpRequest);

基本上,我分别构建内容,添加 body 和设置 header。然后我将身份验证 header 添加到 httpRequest object。所以我必须将内容 headers 添加到 httpContent object 并将授权 header 添加到 httpRequest object.