Search code examples
c#.net-corepostpostasync

HttpClient PostAsync not working but can post request by Postman


I am using httpClient.PostAsync to post my request but it is not working. I tried same request header and body with Postman and it is working well.

I have checked in fiddler for request, below is from Postman request which can successfully post request to server.

enter image description here

But when I call same request from PostAsync, it returns Internal Server Error

enter image description here

Below is my implementation

public virtual async Task<OrderResponseDto> PostAsync(PlaceOrdersDto orderRequest, string namedClient, string queryString, string sessionTokenHeader)
{

   var content = new StringContent(JsonSerializer.Serialize(orderRequest));
   content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); ;
   var client = clientFactory.CreateClient(namedClient);
   client.DefaultRequestHeaders.Add("x-session-token", sessionTokenHeader);                 
   var httpResponse = await client.PostAsync(queryString, content);              
   Console.WriteLine(httpResponse.Content.ReadAsStringAsync().Result);              
}

I have also tried by adding Encoding and accept header like below

var content = new StringContent(JsonSerializer.Serialize(orderRequest), System.Text.Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

But this also didnt worked. What I am missing?


Solution

  • In your C# request, the User-Agent header is missing. It typically shouldn't be an issue, but seems that this server requires it for proper functioning. Without it, you'll encounter a 500 error. You can verify this by testing the request in your Postman request.