6

I have a very simple C# Http Client console app, which needs to do an HTTP POST of a json object to a WebAPI v2. Currently, My app can do the POST using FormUrlEncodedContent:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Net.Http.Formatting;


namespace Client1
{
    class Program
    {
        class Product
        {
            public string Name { get; set; }
            public double Price { get; set; }
            public string Category { get; set; }
        }
        static void Main(string[] args)
        {
             RunAsync().Wait();
        }
        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:8888/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var content = new FormUrlEncodedContent(new[] 
                        {
                            new KeyValuePair<string, string>("Category", "value-1"),
                            new KeyValuePair<string, string>("Name", "value-2")                           
                       });

                var result = client.PostAsync("Incident", content).Result;      
                var r = result;     
            }
        }
    }
}

However, when I try to use JSON in the POST body, I get error 415 - Unsupported media Type:

class Product
{
    public string Name { get; set; }
    public double Price { get; set; }
    public string Category { get; set; }
}

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
var  response = await client.PostAsJsonAsync("api/products", gizmo);

Doing explicit JSON serialization does not change the outcome for me:

string json = JsonConvert.SerializeObject(product);
var  response = await client.PostAsJsonAsync("api/products", json);

What is the proper way to handle this, and to be able to POST JSON?

6
  • 1
    Do you own the server implementation? 415 - Unsupported media Type is a server-side error where it's saying it doesn't support JSON, so unrelated to your client code. Commented Aug 25, 2016 at 0:39
  • Yes, My server side is an OData controller: [HttpPost] public void Post([FromBody] Product value) { var req = Request; var p = value; } Commented Aug 25, 2016 at 0:42
  • 1
    Yes, but is your server project configured to accept and return JSON? Take a look at adding headers to your request to denote that you're sending JSON as well. Commented Aug 25, 2016 at 0:44
  • Just to confirm since I don't see it in the code that you're having a problem with, did you still set the media type like you did in the code snippet where it worked? client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Commented Aug 25, 2016 at 1:05
  • 1
    this client code still gives me 415: var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" }; var json = JsonConvert.SerializeObject(gizmo); var response = await client.PostAsJsonAsync("/Incident", new StringContent(json, Encoding.UTF32, "application/json")); Commented Aug 25, 2016 at 1:08

2 Answers 2

4

When I am posting FormUrlEncodedContent this is the extent of the code I am using

        HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            {"grant_type", "password"},
            {"client_id", _clientId},
            {"client_secret", _clientSecret},
            {"username", _userName},
            {"password", _password}
        }
            );

            var message =
                await httpClient.PostAsync(_authorizationUrl, content);

where _authorizationUrl is an an absolute url.

I am not setting any of these properties

           client.BaseAddress = new Uri("http://localhost:8888/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

like you are.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. This is what I said in my answer below. But no idea why someone down-voted it.
3

If you expect it to send as FormUrlEncodedContent, then MediaTypeWithQualityHeaderValue("application/json") is wrong. This will set the request content-type to json. Use application/x-www-form-urlencoded instead or just do not set MediaTypeWithQualityHeaderValue at all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.