Error sending json in POST to web API service

134,800

Solution 1

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

Solution 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.

Solution 3

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.

Share:
134,800
GVillani82
Author by

GVillani82

Passionate about mobile development, clean code and reactive programming

Updated on July 08, 2022

Comments

  • GVillani82
    GVillani82 almost 2 years

    I'm creating a web service using Web API. I implemented a simple class

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

    And then I have implemented inside my controller

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

    But when I call the API passing in POST the file json:

    {"code":"XXX-542","indexValue":"3","primaryCodeReference":"7"}
    

    I obtain the following error message:

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

    What am I doing wrong?

  • War
    War over 8 years
    The question is specifically about a http POST, he's not requesting data from the server he's sending data to the server.