1

I had a console application that was working perfectly fine before the .NET framework was upgraded. The console application calls a web API. It used to use Newtonsoft.Json. As the method PostAsJsonAsync is no longer in the System.Net.Http.dll (.NET 4.5.2), the PostAsJsonAsync has to be replaced:

HttpResponseMessage responseMessage = await client.PostAsJsonAsync(url, myRequest);

According to the solution at HttpClient not supporting PostAsJsonAsync method C# (rather than follow the accepted answer, I've followed the second-highest voted answer which the users commented should be the accepted answer), I've tried to replace it with PostAsync:

            var values = new Dictionary<string, string>
            {
                { "myRequestNo", myRequest.requestNo.ToString() },
                { "myImage", myRequest.image },
            };
            var json = JsonConvert.SerializeObject(values, Formatting.Indented);
            var stringContent = new StringContent(json);

            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
        var response = await client.PostAsync(url, stringContent);
        var responseString = await response.Content.ReadAsStringAsync();

I can see the following header was successfully added to the request:

From Visual Studio

Despite adding this header, I get the following error:

The request entity's media type 'text/plain' is not supported for this resource

What am I missing?

Zesty
  • 2,922
  • 9
  • 38
  • 69

2 Answers2

2

Your problem is that you are setting that you would like to accept application/json

What you should instead be doing is state that the stringcontent is application/json this is done using the following code:

stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

this tells the server that the content type it can expect in the body is "application/json"

0

Remove:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

And replace it with:

client.DefaultRequestHeaders.Add("ContentType", "application/json");
Edney Holder
  • 1,140
  • 8
  • 22