【发布时间】:2013-09-09 20:33:38
【问题描述】:
我的客户端(一个 ASP.NET MVC 应用程序)通过调用我的 ASP.NET Web API 得到这个错误。我检查了,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);
}
}
}
【问题讨论】:
-
您是否尝试过为您发出的 http 请求设置内容类型?
-
尝试将返回类型从 IEnumerable 切换为 List
-
看起来是这样 - 你见过stackoverflow.com/questions/10428177/…
-
@justnS 您没有为 GET 请求设置内容类型。仅当您发送正文时,即 PUT、POST、PATCH。
标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api