HttpClient keeps receiving bad request

In my case examining the content of result.Content.ReadAsStringAsync().Result had the cause of the problem informing of some missing parameters and some parameters with invalid values. Corrected and it's working now.


Okay, I figured out the issue I was having. It seems that Serializing my JSON object into a string first, then posting it with PostAsJsonAsync was leaving all of the escape (\) characters in my object, which was why I received the Bad Request.

The problem here was my first key/value pair in my JSON object had a key with the @ symbol in it. If I try to just PostAsJsonAsync with the object, I lost the @ symbol, which gave me a Bad Request also.

What I ended up doing was Serializing the object into a string as seen above, then I converted it the a Byte Array and then created a new ByteArrayContent object passing in my byte array, adding the ContentType attribute to the ByteArrayContent Headers, then using PostAsync instead of PostAsJsonAsync. This worked perfectly.

Here is the code:

public JobResponse RunInformaticaJob(JobRequest jobRequest)
    {
        try
        {
            client = new HttpClient();
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
            client.DefaultRequestHeaders.TryAddWithoutValidation("icSessionId", icSessionId);

            string message = JSONSerializer.Serialize(jobRequest);
            message = message.Insert(1, "\"@type\": \"job\",");
            byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(message);
            var content = new ByteArrayContent(messageBytes);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            var response = client.PostAsync(loggedUser.serverUrl + "/api/v2/job", content).Result;
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsAsync<JobResponse>().Result;
            }
            else
            {
                var result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(result);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        return null;
    }

Issue resolved!

Tags:

C#

.Net