No MediaTypeFormatter 'text / html' available

I wrote a ServiceHelper class that will help POST in 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 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?

+3


source to share


2 answers


Ok, the problem was that the .NET application pool version was set to 2.0, whereas the web API was written for .NET version 4.0, I changed the version and now it works as expected.



It is worth noting that it is recommended to name response.EnsureSuccessStatusCode()

as stated in the answer below.

+3


source


Obviously the server is returning HTML where you expect JSON and there is obviously no way to deserialize TResponse

from HTML ...

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



You should call response.EnsureSuccessStatusCode()

to make sure the answer shows success (usually 200 OK). If it is not, it will throw an exception.

+7


source







All Articles