prasanna p

prasanna p

  • 1.3k
  • 470
  • 105.2k

Web API : always showing message content type must be application/json

Sep 3 2020 6:52 AM
Hi friends,
 
I am trying to get the data from API using post method.It has Http headers and json parameters.
Tested API in the postman it is working.
 
In the development, the response status is showing success and status code is 200 (ok) but the responsemessage always showing content type must be application/json.I tested with diiferent ways to get the data.
 
Please check the following code :
  1. HttpClient client = new HttpClient();  
  2. client.BaseAddress = new Uri("apiurl");  
  3. client.DefaultRequestHeaders.Accept.Clear();  
  4. client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type""application/json");  
  5. client.DefaultRequestHeaders.TryAddWithoutValidation("Cache-control""no-cache");  
  6. var json = new person() { fromdate = "01/08/2020", todate = "20/08/2020", locationcode= "1234", accessKey= "12345" };  
  7. var request = new HttpRequestMessage(HttpMethod.Post, "apiurl")  
  8. {  
  9. Content = new StringContent(JsonConvert.SerializeObject(json), Encoding.UTF8, "application/json")  
  10. };  
  11. var response = client.SendAsync(request).Result;  
  12. if (response.ReasonPhrase == "OK")  
  13. {  
  14. var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);  
  15. }  
I added header and parameters like this also
  1. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
I tried by adding headers to request also but result is not getting fron the API.
  1. request.Content = new StringContent("{\"fromdate\":\"01/08/2020\",\"todate\":\"20/08/2020\",\"locationcode\":\"1234\",\"accessKey\":\"12345\"}",  
  2. Encoding.UTF8,  
  3. "application/json"); 
Always showing content type must be application/json.
 
Please help me on this how to get the data from API.

Answers (4)