向Web API服务发送POST请求时发送JSON出错。

91
我正在使用Web API创建一个网络服务。我实现了一个简单的类。
public class ActivityResult
{
    public String code;
    public int indexValue;
    public int primaryCodeReference;
}

然后我在控制器内部实现了它。

[HttpPost]
public HttpResponseMessage Post(ActivityResult ar)
{
    return new HttpResponseMessage(HttpStatusCode.OK);
}

但是当我通过POST方式调用API并传递json文件时:
{"code":"XXX-542","indexValue":"3","primaryCodeReference":"7"}

我收到了以下错误信息:
{
    "Message": "The request entity's media type 'text/plain' is not supported for this resource.",
    "ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'ActivityResult' from content with media type 'text/plain'.",
    "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",
    "StackTrace": "   in System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   in System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   in System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}

我做错了什么?


9
你需要在有效载荷上添加一个“application/json”的头部,以便从客户端接受该有效载荷。 - Adam Zuckerman
我已经正确设置了HTTP请求中的标头。然而问题似乎是服务器端的:https://www.dropbox.com/s/xlidnnybs8v6d0u/Cattura.JPG - GVillani82
4
看起来你只设置了Accept头为application/json。你还需要设置Content-Type头为application/json - Brian Rogers
6个回答

186
在HTTP请求中,您需要将Content-Type设置为: Content-Type:application / json 因此,如果您使用Fiddler客户端,请在请求头添加 Content-Type:application / json

2
  1. You have to must add header property Content-Type:application/json
  2. When you define any POST request method input parameter that should be annotated as [FromBody], e.g.:

    [HttpPost]
    public HttpResponseMessage Post([FromBody]ActivityResult ar)
    {
      return new HttpResponseMessage(HttpStatusCode.OK);
    }
    
  3. Any JSON input data must be raw data.


1

另一个提示...在Composer/Parsed选项卡的文本框字段中添加"content-type: application/json"的位置。那里已经填写了3行,所以我将这个Content-type作为第4行添加。这使得Post工作。


0

我在被接受的答案中已经涵盖了所有设置。 我的问题是,我试图更新实体框架实体类型“Task”,如下:

public IHttpActionResult Post(Task task)

我的解决方法是创建自己的实体“DTOTask”,如下所示:
public IHttpActionResult Post(DTOTask task)

0
请检查您是否将方法传递为POST而不是GET。 如果是,您将会得到与您上面发布的相同的错误。
$http({               
 method: 'GET',

请求实体的媒体类型"text/plain"不受此资源支持。

1
这个问题特别涉及到 HTTP POST,他不是从服务器请求数据,而是向服务器发送数据。 - War

0

在 Web API 请求头部分中,如果没有提及任何内容,则需要包含 Content-Type:application/json。否则默认传递的是 Content-Type:text/plain

在 Postman 工具上测试 API 的最佳方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接