【问题标题】:Web API: No MediaTypeFormatter is available to read an object of type 'IEnumerable`1' from content with media type 'text/plain'Web API:没有 MediaTypeFormatter 可用于从媒体类型为“text/plain”的内容中读取类型为“IEnumerable`1”的对象
【发布时间】: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


【解决方案1】:

我相信(因为我现在没有时间测试它)您需要在您传递给HttpResponseException 的 responseMessage 上显式设置状态代码。通常,HttpResponseException 会为您设置状态码,但由于您明确提供了响应消息,它将使用其中的状态码。默认情况下,`HttpResponseMessage 的状态码为 200。

所以发生的情况是您在服务器上遇到错误,但仍然返回 200。这就是为什么您的客户端试图反序列化 StringContent 生成的文本/纯正文,就好像它是一个 IEnumerable。

你需要设置

responseMessage.StatusCode = HttpStatusCode.InternalServerError

在服务器上的异常处理程序中。

【讨论】:

    【解决方案2】:

    如果您的 WebAPI 期望以纯文本形式返回内容,那么只使用 ReadAsStringAsync 怎么样?

    response.Content.ReadAsStringAsync().Result;
    

    【讨论】:

    • 如果服务器失败,OP 只需要一个字符串。我认为您上面的行实际上不会编译。
    猜你喜欢
    • 1970-01-01
    • 2012-09-12
    • 2016-06-29
    • 1970-01-01
    • 2018-05-29
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多