我通过调用我的 ASP.NET Web API 在我的客户端(一个 ASP.NET MVC 应用程序)中收到此错误。我检查了一下,Web API 正在返回数据。
No MediaTypeFormatter is available to read an object of type
'IEnumerable`1' from content with media type 'text/plain'.
我相信我可以继承DataContractSerializer
并实现我自己的序列化程序,它可以将Content-Type
HTTP 标头附加为text/xml
.
但我的问题是:有必要吗?
因为如果是,则意味着默认情况下DataContractSerializer
不会设置此基本标头。我想知道微软是否可以忽略这么重要的事情。还有其他出路吗?
这是相关的客户端代码:
public ActionResult Index()
{
HttpClient client = new HttpClient();
var response = client.GetAsync("http://localhost:55333/api/bookreview/index").Result;
if (response.IsSuccessStatusCode)
{
IEnumerable<BookReview> reviews = response.Content.ReadAsAsync<IEnumerable<BookReview>>().Result;
return View(reviews);
}
else
{
ModelState.AddModelError("", string.Format("Reason: {0}", response.ReasonPhrase));
return View();
}
}
这是服务器端(Web API)代码:
public class BookReviewController : ApiController
{
[HttpGet]
public IEnumerable<BookReview> Index()
{
try
{
using (var context = new BookReviewEntities())
{
context.ContextOptions.ProxyCreationEnabled = false;
return context.BookReviews.Include("Book.Author");
}
}
catch (Exception ex)
{
var responseMessage = new HttpResponseMessage
{
Content = new StringContent("Couldn't retrieve the list of book reviews."),
ReasonPhrase = ex.Message.Replace('\n', ' ')
};
throw new HttpResponseException(responseMessage);
}
}
}