Search code examples
c#asp.net-web-apirequesthttpclient

Send a json on a post request with HttpClient and C#


I have a problem with this code, my goal is to send a modification via an API so I'm doing a request over HttpClient.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

public class patchticket
{
   public string patch(string ticketid)
   {

       using (var httpClient = new HttpClient())
       {
           using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://desk.zoho.com/api/v1/tickets/"+ticketid))
           {
               request.Headers.TryAddWithoutValidation("Authorization", "6af7d2d213a3ba5e9bc64b80e02b000");
               request.Headers.TryAddWithoutValidation("OrgId", "671437200");

               request.Content = new StringContent("{\"priority\" : \"High\"}", Encoding.UTF8, "application/x-www-form-urlencoded");


               var response =  httpClient.SendAsync(request);
           return response

           }
       }

   }
}

The result is that I don't have any error, but changes doesn't take effect.

The credentials are okay, I have tested it with curl with the same parameters and it works great.


Solution

  • It looks like you want to post a json in the request. Try to define the right content-type that is application/json. For sample:

    request.Content = new StringContent("{\"priority\" : \"High\"}",
                                        Encoding.UTF8, 
                                        "application/json");
    

    Since your method returns a string it can be a a non-async method. The method SendAsync is async and you have to wait the request finished. You could try to call Result after the request. For sample:

    var response = httpClient.SendAsync(request).Result;
    return response.Content; // string content
    

    And you will get an object of HttpResponseMessage. There are a lot of useful information about the response on it.

    Anyway, since it's an IO bound operation, it's better to use the async version like this:

    var response = await httpClient.SendAsync(request);
    return response.Content; // string content