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>();