Does not display data on Api web screen asp.net mvc

0

I started to study a little web api using with asp.net, I am doing a very simple example where I just want to list the data of 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);
    }
    
asked by anonymous 02.03.2018 / 00:57

1 answer

2

Change ReadAsAsync by ReadAsStringAsync :

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

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

    
02.03.2018 / 01:59