I'm using System.Net.Http
, I found several examples on the web. I managed to create this code for make a POST
request:
public static string POST(string resource, string token)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "")
});
var result = client.PostAsync("", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
return resultContent;
}
}
all working fine. But suppose that I want pass a third param to the POST
method, a param called data
. The data param is an object like this:
object data = new
{
name = "Foo",
category = "article"
};
how can I do that without create the KeyValuePair
? My php RestAPI
wait a json input, so the FormUrlEncodedContent
should send the raw
json correctly. But how can I do this with Microsoft.Net.Http
? Thanks.
This question is related to
c#
json
dotnet-httpclient
There's now a simpler way with .NET Standard
or .NET Core
:
var client = new HttpClient();
var response = await client.PostAsync(uri, myRequestObject, new JsonMediaTypeFormatter());
NOTE: In order to use the JsonMediaTypeFormatter
class, you will need to install the Microsoft.AspNet.WebApi.Client
NuGet package, which can be installed directly, or via another such as Microsoft.AspNetCore.App
.
Using this signature of HttpClient.PostAsync
, you can pass in any object and the JsonMediaTypeFormatter
will automatically take care of serialization etc.
With the response, you can use HttpContent.ReadAsAsync<T>
to deserialize the response content to the type that you are expecting:
var responseObject = await response.Content.ReadAsAsync<MyResponseType>();
@arad good point. In fact I just found this extension method (.NET 5.0):
PostAsJsonAsync<TValue>(HttpClient, String, TValue, CancellationToken)
So one can now:
var data = new { foo = "Hello"; bar = 42; };
var response = await _Client.PostAsJsonAsync(_Uri, data, cancellationToken);
In .NET 5, a new class has been introduced called JsonContent
, which derives from HttpContent
. See in Microsoft docs
This class has a static method called Create()
, which takes an object as a parameter.
Usage:
var myObject = new
{
foo = "Hello",
bar = "World",
};
JsonContent content = JsonContent.Create(myObject);
HttpResponseMessage response = await _httpClient.PostAsync("https://...", content);
You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent
. One way to do so is to serialize it into a JSON string:
var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json
Now all you need to do is pass the string to the post method.
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+
var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);
A simple solution is to use Microsoft ASP.NET Web API 2.2 Client
from NuGet.
Then you can simply do this and it'll serialize the object to JSON and set the Content-Type
header to application/json; charset=utf-8
:
var data = new
{
name = "Foo",
category = "article"
};
var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var response = await client.PostAsJsonAsync("", data);
Source: Stackoverflow.com