4

I cannot get the following POST request to work. It returns with status message 400 (Bad Request), no matter what I try.

static HttpClient client = new HttpClient();

   client.BaseAddress = new Uri("<<REDACTED>>"); 
   client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

   // authorisation credentials go here, which work

  var model = JsonConvert.SerializeObject(dialApi); //, Encoding.UTF8, "application/json"); //.DeserializeObject<Hello>(result);
  var model1 = new StringContent(model, Encoding.UTF8, "application/json");
  var x = "{\"data\":{\"Dest\":\"<<REDACTED>>\"}}";

  //HttpResponseMessage response = await client.PostAsJsonAsync(path, model1);
  HttpResponseMessage response = await client.PostAsJsonAsync(path, new StringContent(x, Encoding.UTF8, "application/json"));

The problem could be that the 'Content' -> 'Headers' --> 'ContentType' is 'text/html' (it should be 'application/json', but I cannot seem to change this. The default headers are already setup to 'application/json'

enter image description here

I should add that I have the API working in Postman, with the body sent as 'application/json' with the raw setting:

enter image description here

I wonder if anyone can help?

Update:

I have tried the alternative implementation given in the answer of the 'duplicate' question, which also does not work:

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, path);
        request.Content = new StringContent("{\"data\":{\"Dest\":\"<<>>redacted\"}}",
                                Encoding.UTF8,
                                "application/json");//CONTENT-TYPE header

        await client.SendAsync(request)
                  .ContinueWith(responseTask =>
                  {
                      Console.WriteLine("Response: {0}", responseTask.Result);
                  });

With the following printed to the console:

enter image description here

Winthorpe
  • 892
  • 2
  • 17
  • 33
  • Maybe: https://stackoverflow.com/questions/10679214/how-do-you-set-the-content-type-header-for-an-httpclient-request – Felipe Oriani Nov 21 '18 at 13:05
  • 1
    In your screenshot, are you checking the `Content` of the response? That could very well be text/html as it as the error message you got. – JLe Nov 21 '18 at 13:07
  • 1
    Use [HttpClient.PostAsync](https://learn.microsoft.com/en-us/uwp/api/windows.web.http.httpclient.postasync) instead of `PostAsJsonAsync`. Your payload is already a JSON string – Panagiotis Kanavos Nov 21 '18 at 13:08
  • @JLe - Yes it could be caused by the error response. – Winthorpe Nov 21 '18 at 13:09
  • @Winthorpe use Fiddler or a similar debugging proxy to see what's actually being sent. `PostAsJsonAsync` is definitely not needed when you perform your own serialization. `client.PostAsync(model1)` is enough. BTW `Content-Type` is a content, not a request header. Using `DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); ` results in a bad request – Panagiotis Kanavos Nov 21 '18 at 13:11
  • Thanks for your comments. I have tried 'HttpResponseMessage response = await client.PostAsync(path, model1);' which also doesn't work. – Winthorpe Nov 21 '18 at 13:22
  • I have a get request which works. The problem is with the POST – Winthorpe Nov 21 '18 at 13:22
  • Did you solve this? @Winthorpe i am having the same issue – Dev Mar 02 '22 at 09:16
  • @Decoder94 - I'm afraid I can recall what the solution was. I haven't used the httpClient in .NET for a long time. – Winthorpe Mar 02 '22 at 12:29
  • try this approach,It works private static async Task PostJsonContent(string uri, HttpClient httpClient) { var postUser = new User { Name = "Steve Gordon" }; var postRequest = new HttpRequestMessage(HttpMethod.Post, uri) { Content = JsonContent.Create(postUser) }; var postResponse = await httpClient.SendAsync(postRequest); postResponse.EnsureSuccessStatusCode(); } – Shreekanth Gaanji Sep 06 '22 at 13:49

0 Answers0