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

1.3k views Asked by At

I am trying to use Zendesk's ticket submission API and in their documentation they give the following example in cURL:

curl https://{subdomain}.zendesk.com/api/v2/tickets.json \ -d '{"ticket": {"requester": {"name": "The Customer", "email": "[email protected]"}, "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

I'm trying to make this POST request using the System.Net.Http library:

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);

I keep getting an error when I try to add the Authorization header to the content. I understand now that HttpContent is only supposed to contain content type headers.

How do I create and send a POST request where I can set the Content-Type header, the Authorization header, and include Json in the body using the System.Net.Http library?

1

There are 1 answers

0
Adam On BEST ANSWER

I used the code below to build my request:

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);

Basically, I build the content separately adding the body and setting the header. I then added the authentication header to the httpRequest object. So i had to add the content headers to the httpContent object and the authorization header to the httpRequest object.