skip to Main Content

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


  1. If you built the Web Api change its response from

    "data": [
    {
      "id": 1,
      "countryName": "Afghanistan"
    },
    {
      "id": 2,
      "countryName": "Albania"
    },
    {
      "id": 3,
      "countryName": "Algeria"
    }]
    

    To

     [
            {
              "id": 1,
              "countryName": "Afghanistan"
            },
            {
              "id": 2,
              "countryName": "Albania"
            },
            {
              "id": 3,
              "countryName": "Algeria"
            }
    ]
    
    Login or Signup to reply.
  2. Create the object and cast it from json response to object

    public class Data
        {
            public int id { get; set; }
            public string countryName { get; set; }
        }
    
        public class Root
        {
            public List<Data> data { get; set; }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search