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.
using
for theHttpClient
. aspnetmonsters.com/2016/08/2016-08-27-httpclientwrongusing
should not be used:HttpClient is intended to be instantiated once and reused throughout the life of an application. The following conditions can result in SocketException errors: Creating a new HttpClient instance per request. Server under heavy load. Creating a new HttpClient instance per request can exhaust the available sockets.
learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/….Result
will deadlock in any environment that has a synchronization context.