小编典典

在POST中将JSON发送到Web API服务时出错

json

我正在使用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)"
}

我究竟做错了什么?


阅读 330

收藏
2020-07-27

共1个答案

小编典典

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

因此,如果您使用的是提琴手客户端,请添加Content-Type: application/json到请求标头中

2020-07-27