Search code examples
c#postmanhttprequesthttpclient

What would be a built-in alternative to using RestSharp for the following code?


I have a requirement to send the following but using built in .NET classes, HttpClient preferably.

I tried with Httpclient, HttpRequestMessage, HttpResponseMessage and SendAsync but I get errors of missing JSON. While calling it with the same params from Postman works fine.

Maybe I am using the wrong classes?

    var client = new RestClient("myurl");
    var request = new RestRequest(Method.POST);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("channelId", "mytestid");
    request.AddHeader("Authorization", "big access token");
    request.AddHeader("Content-Type", "application/json");
    request.AddHeader("Accept", "application/json");
    request.AddParameter("undefined", "{\n  \"jsonrequesthere\":...}", ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);

Solution

  • Should be as simple as

    var client = new HttpClient(); // ideally this would be created from IHttpClientFactory
    var request = new HttpRequestMessage(HttpMethod.Post, "myurl");
    
    request.Headers.Add("cache-control", "no-cache");
    request.Headers.Add("channelId", "mytestid");
    request.Headers.Add("Authorization", "big access token");
    request.Headers.Add("Accept", "application/json");
    
    request.Content = new StringContent(json, null, "application/json");
    // or request.Content = JsonContent.Create(SomeObjectToSerialize);
    
    var response = await client.SendAsync(request);
    var result = await response.Content.ReadAsStringAsync();
    

    Note : There are many other built in ways to achieve the same thing. Though at this stage in your learning you are better to just read the documentation

    Full Demo Here