![](/img/trans.png)
[英]No MediaTypeFormatter is available to read an object of type 'IEnumerable`1' from content with media type 'text/html in asp.net mvc webapi
[英]No MediaTypeFormatter is available '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)。 如果情況並非如此,則會引發異常。
好的,問題是應用程序池的.NET版本設置為2.0版,而Web API是為.NET 4.0編寫的,我更改了版本,現在它正在按預期工作。
值得注意的是,調用response.EnsureSuccessStatusCode()
是一個好主意,如下面的答案中所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.