No MediaTypeFormatter is available 'text/html&

2019-07-05 02:49发布

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?

2条回答
Root(大扎)
2楼-- · 2019-07-05 03:15

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.

查看更多
祖国的老花朵
3楼-- · 2019-07-05 03:23

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.

查看更多
登录 后发表回答