Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No MediaTypeFormatter is available 'text/html'

I have written a ServiceHelper class that will assist with POST's to a C# Web API controller

public class ServiceHelper<TResponse, TRequest> : IServiceHelper<TResponse, TRequest>
{
    public TResponse Execute
        (
        string endpoint, 
        string controller, 
        string action, 
        TRequest request,
        string format = "application/json"
        )
    {
        using (var httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri(endpoint);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(format));

            var response = httpClient.PostAsJsonAsync(String.Format("{0}/{1}", controller, action),
                request).Result;

            return response.Content.ReadAsAsync<TResponse>().Result;
        }
    }
}

I keep on getting

Additional information: No MediaTypeFormatter is available to read an object of type 'ReadMotorVehiclesWorkflowResponse' from content with media type 'text/html'.

Any ideas on how to fix this?

like image 300
Andre Lombaard Avatar asked Aug 07 '14 13:08

Andre Lombaard


2 Answers

Apparently the server returns HTML where you expect JSON, and obviously there is no way to deserialize a TResponse from HTML...

I suspect the server is actually returning an error code, and the HTML is just a visual representation of the error.

You should call response.EnsureSuccessStatusCode() to make sure the response indicates success (typically 200 OK). If it's not the case, it will raise an exception.

like image 168
Thomas Levesque Avatar answered Oct 01 '22 18:10

Thomas Levesque


Ok, the problem was that the application pool's .NET version was set to version 2.0 while the web API was written for .NET version 4.0, I changed the version and it is now working as expected.

It is worth while to note that it is a good idea to call response.EnsureSuccessStatusCode() as mentioned in the answer below.

like image 28
Andre Lombaard Avatar answered Oct 01 '22 18:10

Andre Lombaard