1

I have Update my Dot Net Core project from 2.2 to 3.1. It is an MVC project, I have called my .net core API from my MVC project and all of my post method calls gives an error.

Here is the error:

'HttpClient' does not contain a definition for 'PostAsJsonAsync' 
and no accessible extension method 'PostAsJsonAsync' accepting a first argument of type 'HttpClient'
could be found (are you missing a using directive or an assembly reference?

Here is the sample code:

HttpResponseMessage resNews = await client.PostAsJsonAsync("News/GetNews", News);

if (resNews.IsSuccessStatusCode)
{
    UiLogger.LogInfo("News api called");
    var result = resNews.Content.ReadAsStringAsync().Result;
    newsItem = JsonConvert.DeserializeObject<News>(result);
}

Is there any solution or alternative? Thankyou.

jps
  • 20,041
  • 15
  • 75
  • 79
SAGAR SAHA
  • 83
  • 1
  • 9

1 Answers1

5

This works for me.

Dot net core 3.x doesn't have any assembly for PostAsJsonAsync().

And Dot Net Core 2. not supported by Microsoft. So we should not use anything that not in 3.x. should not add assembly from 2.x.

The possible alternative is PostAsync();

HttpResponseMessage resNews = 
await client.PostAsync("News/GetNews", new StringContent(JsonConvert.SerializeObject(Object), 
Encoding.UTF8, "application/json"));
    
If pass only string:
    
  HttpResponseMessage resNews = 
  await client.PostAsync("News/GetNews", new StringContent("string"));
SAGAR SAHA
  • 83
  • 1
  • 9