Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error sending json in POST to web API service

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?

like image 272
GVillani82 Avatar asked Mar 13 '14 16:03

GVillani82


People also ask

How do I post JSON to a REST API endpoint?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How pass JSON object in HTTP GET?

To get JSON from a REST API endpoint, you must send an HTTP GET request and pass the "Accept: application/json" request header to the server, which will tell the server that the client expects JSON in response.

Does Web API return JSON by default?

By default, Web API produces XML but if there is need for JSON, given syntax will do it. Open WebApiConfig. cs file in solution and add mentioned line in it as shown in example.


1 Answers

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

like image 124
beaumondo Avatar answered Sep 19 '22 07:09

beaumondo