【问题标题】:No MediaTypeFormatter is available to read an object of type from content with media type 'text/html'没有 MediaTypeFormatter 可用于从媒体类型为“text/html”的内容中读取类型对象
【发布时间】:2018-05-29 01:12:58
【问题描述】:

运行 Core 2.0 Web Api。当我通过邮递员发布到我的控制器时,一切都在本地正常工作。但是我得到:

没有 MediaTypeFormatter 可用于读取“消息”类型的对象 来自媒体类型为“text/html”的内容

部署到生产服务器时

控制器:

    [HttpPost]
    public void Post([FromQuery] Message message)
    {
        _service.UserRequest(message);
    }

消息:

public class Message : IEntity
{
    public string To { get; set; } = string.Empty;
    public string From { get; set; } = string.Empty;
    public string Body { get; set; } = string.Empty;
}

不确定是什么原因造成的。是 IIS 配置中的 mime 类型吗?

【问题讨论】:

    标签: .net asp.net-core-webapi asp.net-core-2.0


    【解决方案1】:

    我尝试了上一个答案的这个变体,目的是收紧代码:

    var obj = await response.Content.ReadAsAsync<T>( new [] { new JsonMediaTypeFormatter() });
    

    但是,它仍然抱怨我,因为响应仍然没有正确的内容标题。

    所以,我尝试了这个来更改标题,这对我有用,但我真的不知道这是否有任何我还没有想到的意外副作用:

    if(response.Content?.Headers?.ContentType != null)
    {
        response.Content.Headers.ContentType.MediaType = "application/json";
    }
    

    【讨论】:

      【解决方案2】:

      这修复了它(添加了新的格式化程序):

              var obj = await response.Content.ReadAsAsync<T>(
                  new List<MediaTypeFormatter>
                  {
                      new XmlMediaTypeFormatter(),
                      new JsonMediaTypeFormatter()
                  });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-03
        • 2012-09-12
        • 2016-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-26
        相关资源
        最近更新 更多