没有媒体类型格式化程序可用于从媒体类型为 'text/html' 的内容中读取类型的对象



运行Core 2.0 Web API。当我通过Postman发布到控制器时,本地一切正常。但是我得到:

没有可读取类型"消息"对象的介体形式图 来自媒体类型的内容" 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 [] { new JsonMediaTypeFormatter() });

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

所以,我尝试更改标题,这对我有用,但是我真的不知道这是否具有我还没有考虑的任何意外副作用:

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

修复了它(添加了新的格式):

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

最新更新