Search code examples
c#jsonhttp-posthttpclient

C# Not able to post data using HttpRequestMessage and getting 400 status


I tried a few different ways I can't get pipelineId to post (receive 400), see code below:

{
                client.BaseAddress = new Uri(_serviceConfig.DataGapsBaseUrl);
                var request = new HttpRequestMessage(HttpMethod.Post, "/piper/jobs");

                var jsonContent = new StringContent(JsonConvert.SerializeObject(new
                {
                    pipelineId = _serviceConfig.DataPipelineId
                }), Encoding.UTF8, "application/json");
                
                request.Content = jsonContent;

                var token = await GetToken();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());

                var result = await client.SendAsync(request);

                var json = JsonConvert.DeserializeObject<JToken>(result.Content.ReadAsStringAsync().Result);
                var jobId = json["id"].ToString();
                return jobId;
            }
        }

When I use Postman same actions as above, I get 200 status and results:

enter image description here


Solution

  • since you are using async await , use it everywhere and this syntax is more usuall

    using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };
    
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());
    
    var jsonContent = new StringContent(JsonConvert.SerializeObject(new
                    {
                        pipelineId = _serviceConfig.DataPipelineId
                    }), Encoding.UTF8, "application/json");
    
     var response = await client.PostAsync(uri, jsonContent);
    
     var json = await response.Content.ReadAsStringAsync();
    
    var jObj = JObject.Parse(json);
    var createTime =  (string) jObj["createTime"]; //I can't see Id in Postman