Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 640
Eugene Goldberg Avatar asked Aug 25 '16 00:08

Eugene Goldberg


People also ask

How do I post JSON data to API using C #?

To post JSON to a REST API endpoint using C#/. NET, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the C#/. NET POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I post a response to JSON?

To post JSON data to the server, we need to use the HTTP POST request method and set the correct MIME type for the body. The correct MIME type for JSON is application/json. In this POST JSON example, the Content-Type: application/json request header specifies the media type for the resource in the body.

How do I make a HTTP POST Web request?

WebRequest wRequest = WebRequest. Create("http://www.example.com/about.aspx"); Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method: wRequest.


1 Answers

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.

like image 190
Developer Avatar answered Sep 20 '22 20:09

Developer