将 JSON 发布到 Web API 2 时出错:此资源不支持请求实体的媒体类型“text/plain”

2024-02-27

我有这门课:

public class MyClass
{
    public MyClass() { Secret = "Don't tell me"; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Description { get; set; }
    private string Secret { get; set; }
}

这个 WEB API 方法:

        // POST api/fixture
    public HttpResponseMessage Post(MyClass value)
    {
        return new HttpResponseMessage(HttpStatusCode.Created);
    }

我已将 Web API 设置为返回 JSON 而不是 XML,并且我没有对默认配置进行任何其他更改。我正在尝试使用 Firefox 的 RESTClient 扩展来测试此方法。这是我的要求:

POST localhost:XXXX/api/fixture
Content-Type: application/json
Accept: application/json
Content-Length: 60

{
 value : { "Name":"Cosby","Age":"13","Description":"OK" }
}

但是我收到这个错误:

{“Message”:“此资源不支持请求实体的媒体类型“text/plain”。”,“ExceptionMessage”:“没有 MediaTypeFormatter 可用于从媒体类型为“text”的内容中读取类型为“MyClass”的对象/plain'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" 在 System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent 内容,类型类型,IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 个格式化程序、IFormatterLogger formatterLogger、CancellationToken CancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request、Type type、IEnumerable`1 个格式化程序、IFormatterLogger formatterLogger、CancellationToken CancellationToken)"}

Edit:

我不明白,因为似乎该方法甚至没有被调用。如果我调试,我会看到构造函数被调用,然后没有调用其他方法。没有例外。

我已经讨论这个问题很长时间了。我发现这个问题通常发生在 Content-Type 设置不正确时,但它似乎不是我的情况,因为请求甚至没有被处理。

任何想法 ?

Thanks


Inside POSTMAN https://www.getpostman.com,只需将设置更改为application/json即可。请参阅下图。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 JSON 发布到 Web API 2 时出错:此资源不支持请求实体的媒体类型“text/plain” 的相关文章

随机推荐