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?
415 - Unsupported media Typeis a server-side error where it's saying it doesn't support JSON, so unrelated to your client code.