HttpClient' does not contain a definition for 'PostAsJsonAsync' and No extension method 'PostAsJsonAsync' accepting a first argument of type 'System.
PostAsJsonAsync<T>(HttpClient, Uri, T) Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON. PostAsJsonAsync<T>(HttpClient, Uri, T, CancellationToken) Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON.
PostAsync(String, HttpContent) Send a POST request to the specified Uri as an asynchronous operation. PostAsync(Uri, HttpContent) Send a POST request to the specified Uri as an asynchronous operation.
Yes, you need to add a reference to
System.Net.Http.Formatting.dll
This can be found in the extensions assemblies area.
A good way of achieving this is by adding the NuGet package Microsoft.AspNet.WebApi.Client
to your project.
PostAsJsonAsync
is no longer in the System.Net.Http.dll
(.NET 4.5.2). You can add a reference to System.Net.Http.Formatting.dll
, but this actually belongs to an older version. I ran into problems with this on our TeamCity build server, these two wouldn't cooperate together.
Alternatively, you can replace PostAsJsonAsync
with a PostAsync
call, which is just part of new dll.
Replace
var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;
With:
var response = client.PostAsync("api/AgentCollection", new StringContent(
new JavaScriptSerializer().Serialize(user), Encoding.UTF8, "application/json")).Result;
Note that JavaScriptSerializer
is in the namespace: System.Web.Script.Serialization
.
You will have to add an assembly reference in your csproj: System.Web.Extensions.dll
See https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836
The missing reference is the System.Net.Http.Formatting.dll
. But the better solution is to add the NuGet package Microsoft.AspNet.WebApi.Client
to ensure the version of the formatting dll worked with the .NET framework version of System.Net.Http
in my project.
As already debatted, this method isn't available anymore since .NET 4.5.2. To expand on Jeroen K's answer you can make an extension method:
public static async Task<HttpResponseMessage> PostAsJsonAsync<TModel>(this HttpClient client, string requestUrl, TModel model)
{
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(model);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
return await client.PostAsync(requestUrl, stringContent);
}
Now you are able to call client.PostAsJsonAsync("api/AgentCollection", user)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With