Does not display data on the Web Api Asp.net mvc screen

Asked

Viewed 68 times

0

I started studying a bit of web api using Asp.net, I’m doing a very simple example where I just want to list the data from the employee table, but I get error: No Mediatypeformatter is available to read an Object of type 'Ienumerable`1' from content with media type 'text/html'.

    public static class GlobalVariables
{
    public static HttpClient WebApiClient = new HttpClient();
    static GlobalVariables()
    {
        WebApiClient.BaseAddress = new Uri("http://localhost:57129/api");
        WebApiClient.DefaultRequestHeaders.Clear();
        WebApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    }
}

Controler Index

        public ActionResult Index()
    {
        IEnumerable<MvcEmpregadosModel> empregadoLista;
        HttpResponseMessage response = GlobalVariables.WebApiClient.GetAsync("Empregados").Result;
        empregadoLista = response.Content.ReadAsAsync<IEnumerable<MvcEmpregadosModel>>().Result;
        return View(empregadoLista);
    }

1 answer

1


Exchange the ReadAsAsyncfor ReadAsStringAsync :

empregadoLista = response.Content.ReadAsStringAsync<IEnumerable<MvcEmpregadosModel>>().Result;

The method ReadAsAsync will try to read some kind of standard MediaTypeFormatter as xml or json but the media type you are using is 'text/html'. Like you’re wearing 'text/html' you need to use the ReadAsStringAsync to read as string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.