c# - 将 POST 中的 json 发送到 Web API 服务时出错

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

public class ActivityResult
{
    public String code;
    public int indexValue;
    public int primaryCodeReference;
}

然后我在我的 Controller 内部实现了

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

但是当我调用 API 时传入 POST 文件 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 添加到请求 header

https://stackoverflow.com/questions/22384354/

相关文章:

javascript - 将 JSON 发送到服务器并返回 JSON,无需 JQuery

javascript - 请求的资源错误中不存在 'Access-Control-Allow-Ori

javascript - JSON Stringify 因 UTC 而更改日期时间

json - 在 VS Code 中,禁用错误 "Comments are not permitte

javascript - JSON 是否应该包含空值

json - AngularJS:工厂 $http.get JSON 文件

python - 如何在单元测试中使用 JSON 发送请求

python - Google App Engine 模型的 JSON 序列化

json - json.js 和 json2.js 的区别

python - 如何在 Python 中美化 JSON?