将json发送到web api服务时出错怎么办?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (27)

我正在使用Web API创建一个Web服务。我实现了一个简单的类

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)"
}

我究竟做错了什么?

提问于
用户回答回答于

在HTTP请求中,需要将Content-Type设置为: Content-Type: application/json

所以如果你使用fiddler客户端添加Content-Type: application/json到请求头

用户回答回答于

另一个技巧......在“Composer / Parsed”选项卡上,将“content-type:application / json”添加到文本框字段。这里已经有3条线了,所以我把这个Content-type添加为第4条线。这使邮报工作。

扫码关注云+社区