No MediaTypeFormatter is available 'text/html'

时间秒杀一切 提交于 2020-01-04 01:19:08

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/25184427/no-mediatypeformatter-is-available-text-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!