C# 没有可用的MediaTypeFormatter';text/html';
我已经编写了一个ServiceHelper类,它将帮助发布到C#Web API控制器C# 没有可用的MediaTypeFormatter';text/html';,c#,asp.net-web-api,C#,Asp.net Web Api,我已经编写了一个ServiceHelper类,它将帮助发布到C#Web API控制器 public class ServiceHelper<TResponse, TRequest> : IServiceHelper<TResponse, TRequest> { public TResponse Execute ( string endpoint, string controller, string
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;
}
}
}
关于如何解决这个问题有什么想法吗?显然,服务器返回的HTML是您期望的JSON格式,显然没有办法从HTML中反序列化
响应
我怀疑服务器实际上返回了一个错误代码,而HTML只是错误的视觉表示
您应该调用
response.ensureAccessStatusCode()
,以确保响应指示成功(通常为200 OK)。如果不是这样,它将引发一个异常。好的,问题是应用程序池的.NET版本被设置为2.0版,而web API是为.NET 4.0版编写的,我更改了版本,它现在可以正常工作
值得一提的是,调用
response.EnsureSuccessStatusCode()
是一个好主意,正如下面的答案中所述。谢谢,收到404错误,所以至少我现在的思路是正确的
Additional information: No MediaTypeFormatter is available to read an object of type 'ReadMotorVehiclesWorkflowResponse' from content with media type 'text/html'.