1
votes

I'm building an ASP.NET MVC 5 razor application that calls a RESTful API web service.. One of the calls in the API uses a POST method. I have this line in my code:

var response = httpClient.PostAsJsonAsync("/api/account/AddUserAccount", item).Result;

Now, I was able to build that line without any errors displaying, but when I build the application, I get

'HttpClient' does not contain a definition for 'PostAsJsonAsync' and no extension method 'PostAsJsonAsync' accepting a first argument of type 'HttpClient' could be found

I've done a search on the error and I've found posts on Stack Overflow that say to add a reference to System.Net.Http.Formatting.dll, but I can't find that DLL on my system. How do I fix this error?

2
I installed that but it didn't fix the problem. Now I get messages about not being able to resolve System.Net.Http and The dependency System.Net.Http.Formatting.Extension 5.2.3 in project TestAccountService does not support framework DNXCore,Version=v5.0.Tony Vitabile
If you're using DNX then you cannot use PostAsJsonAsync method. Try the following: var response = await client.PostAsync("api/values", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(item);, Encoding.UTF8,"application/json"));MaKCbIMKo
I was able to get your second suggestion to compile. Thanks. If you make it an answer I'll give you credit for it.Tony Vitabile
@TonyVitabile - I just summarized all comments into the answer.MaKCbIMKo

2 Answers

2
votes

If you gonna use PostAsJsonAsync method then you need to use following NuGet Package.

However, if you're using DNX that it won't work because it does not support DNX (yet?).

It that case you can do the following:

var response = await client.PostAsync("api/values", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(item);, Encoding.UTF8,"application/json"));

That should help.

0
votes

You're missing an using statement.

using System.Net.Http; /* probably this one */
using System.Net.Http.Headers;

Of course, that using statement is no good, unless you have System.Net.Http.Formatting(.dll) referenced (as you found out in your search)

This dll comes from a nuget package !

Microsoft.AspNet.WebApi.Client

Most recent link:

https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/

The version I have here (where I found my copy of that .dll)

https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/4.0.20710