Publicar JSONObject Con HttpClient Desde Web API


Estoy tratando de publicar un JsonObject usando HttpClient desde Web API. No estoy muy seguro de cómo hacer esto y no puedo encontrar mucho en el camino del código de ejemplo.

Esto es lo que tengo hasta ahora:

var myObject = (dynamic)new JsonObject();
myObject.Data = "some data";
myObject.Data2 = "some more data";

HttpClient httpClient = new HttpClient("myurl");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = httpClient.Post("", ???);

Creo que necesito lanzar mi JsonObject como un StreamContent pero me estoy colgando en ese paso.

Author: Mark, 2011-05-25

5 answers

Con la nueva versión de HttpClient y sin el paquete WebAPI sería:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;

O si lo quieres asíncrono:

var result = await client.PostAsync(url, content);
 219
Author: pomber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-09 20:46:26

La forma más fácil es usar un StringContent, con la representación JSON de su objeto JSON.

httpClient.Post(
    "",
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));
 153
Author: carlosfigueira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-03 16:13:14

Dependiendo de su versión.NET también podría usar el método HttpClientExtensions.PostAsJsonAsync.

Https://msdn.microsoft.com/en-us/library/system.net.http.httpclientextensions.postasjsonasync.aspx

 44
Author: user3285954,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-17 13:33:39

Si usa Newtonsoft.Json:

using Newtonsoft.Json;
using System.Net.Http;
using System.Text;

public static class Extensions
{
 public static StringContent AsJson(this object o)
  => new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}

Ejemplo:

var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
 27
Author: Matthew Steven Monkan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-03 02:06:59

No tengo suficiente reputación para agregar un comentario sobre la respuesta de pomber, así que estoy publicando otra respuesta. Usando el enfoque de pomber seguí recibiendo una respuesta de "400 Solicitudes incorrectas" de una API a la que estaba publicando mi solicitud JSON (Visual Studio 2017,. NET 4.6.2). Finalmente, el problema fue rastreado a la cabecera "Content-Type" producida por StringContent () siendo incorrecta (ver https://github.com/dotnet/corefx/issues/7864).

Tl; dr

Use la respuesta de pomber con una línea extra para configurar correctamente el encabezado de la solicitud:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync(url, content).Result;
 7
Author: anthls,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-28 02:54:50