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

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

我做错了什么?

136684 次浏览

In the HTTP request you need to set Content-Type to: Content-Type: application/json

So if you're using fiddler client add Content-Type: application/json to the request header

another tip...where to add "content-type: application/json"...to the textbox field on the Composer/Parsed tab. There are 3 lines already filled in there, so I added this Content-type as the 4th line. That made the Post work.

Please check if you are were passing method as POST instead as GET. if so you will get same error as a you posted above.

$http({
method: 'GET',

The request entity's media type 'text/plain' is not supported for this resource.

I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:

public IHttpActionResult Post(Task task)

What worked for me was to create my own entity "DTOTask" like:

public IHttpActionResult Post(DTOTask task)
  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.

It require to include Content-Type:application/json in web api request header section when not mention any content then by default it is Content-Type:text/plain passes to request.

Best way to test api on postman tool.