Search code examples
c#jsonapidotnet-httpclient

HTTPClient returns 400 Bad Request but Postman returns 201 in C#


I have the following code for a post request

    [TestMethod]
    public async Task<Tuple<int, string>> PostRequestAdditionalAttributeValid0000()
    {
        string locationPath = solutionDirectory.ToString();
        var jsonText = File.ReadAllText(locationPath + @"\TestJsons\testdata.json");

        using (var client = new HttpClient())
        {
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            
            //Add client header
            client.DefaultRequestHeaders.Add("client_uuid", "2fd77dd8-ed76-4bba-b0e1-5cda454c8d6e");

            var result = await client.PostAsync(urlPost, content);

            int StatusNumber = (int)result.StatusCode;
            string resultContent = await result.Content.ReadAsStringAsync();

            return new Tuple<int, string>(StatusNumber, resultContent);
        }
    }

and in Postman it returns a 201 but HTTPClient returns a 400 response (Bad Request). I have no idea why.

My json is as follows

{       
    "audit_date": "2020-05-13T11:27:10.3187798Z",
    "client_uuid": "2fd77dd8-ed76-4bba-b0e1-5cda454c8d6e",
    "audit_entry": {
        "where_uri": "test.com/apps/171f0841-825b-4964-8f8c-0869650f14a6",
        "why_uri": "test.com/reference/reasons_for_change/61acc173-7168-4ae5-9f04-afa228941f8b",
        "who_uri": "test.com/users/4977dae1-a307-425f-980c-53413fef1b0f",
        "when_audited": "2018-11-13T20:20:39+00:00",
        "what_uri": "test.com/tests/1bc67a71-8549-4ab8-9dd9-e44238198860",
        "what_changed": [
            {
                "attribute_name": "birth_year",
                "attribute_value": "1969",
                "attribute_change": null
            },
            {
                "attribute_name": "subject_reference",
                "attribute_value": "TEST-WOO3444",
                "attribute_change": null
            }
        ]
    }    
}

Any help much appreciated. I've googled and read other similar questions, even tried solutions from other stackoverflow posts but none seem to work.

This is the error I am getting alongside the 400 Bad request

Object reference not set to an instance of an object.

After stepping through this line of code

var result = await client.PostAsync(urlPost, content);

Solution

  • thanks for all the ideas, turns out my json was slightly different for postman and my code, so the 400 bad request was actually the correct outcome for the json I was passing in. (I missed a mandatory field)

    Sorry for the trouble.