简体   繁体   中英

how to properly perform HTTP Post of a JSON object using C# HttpClient?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM