c# – 没有MediaTypeFormatter可用’text / html’

我编写了一个ServiceHelper类,它将帮助POST到C#Web API控制器

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;
        }
    }
}

我继续得到

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

有想法该怎么解决这个吗?

最佳答案
显然,服务器返回您期望JSON的HTML,显然无法从HTML反序列化TResponse …

我怀疑服务器实际上是返回错误代码,而HTML只是错误的直观表示.

您应该调用response.EnsureSuccessStatusCode()以确保响应指示成功(通常为200 OK).如果情况并非如此,则会引发异常.

转载注明原文:c# – 没有MediaTypeFormatter可用’text / html’ - 代码日志