没有 MediaTypeFormatter 可用于从媒体类型 'text/html' 的内容中读取类型的对象

No MediaTypeFormatter is available to read an object of type from content with media type 'text/html'

运行 核心 2.0 网络 Api。当我 post 通过 Postman 连接到我的控制器时,在本地一切正常。但是我得到:

No MediaTypeFormatter is available to read an object of type 'Message' from content with media type '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 类型吗?

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

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

我尝试了以前答案的这个变体,目的是加强代码:

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

然而,它仍然为我抱怨,因为响应仍然没有正确的内容header。

所以,我试过这个来改变 headers,这对我有用,但我真的不知道这是否有任何我还没有想过的意想不到的副作用:

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