When I consume a Web API in the MVC project I encountered this error, but I cannot fix it. How can I solve this?
My API is clearly working but MVC implementation doesn’t work.
Controller
public async Task<IActionResult> ListCountries()
{
List<Country> countries = new List<Country>();
HttpClient _client = new HttpClient();
HttpResponseMessage _response = new HttpResponseMessage();
_client = _apiHelper.Initial();
_response = await _client.GetAsync("api/Countries/getall");
if (_response.IsSuccessStatusCode)
{
var results = _response.Content.ReadAsStringAsync().Result;
countries = JsonConvert.DeserializeObject<List<Country>>(results);
}
return View(countries);
}
JSON Data
"data": [
{
"id": 1,
"countryName": "Afghanistan"
},
{
"id": 2,
"countryName": "Albania"
},
{
"id": 3,
"countryName": "Algeria"
}
]
2
Answers
If you built the Web Api change its response from
To
Create the object and cast it from json response to object