31

How do I / is it possible to pass in a json object to a webapi controller (POST) and not have a class to map it to, but rather handle it as arbitrary content?

So if I pass in from my client like so:

        createRecord: function (model, data, callback, callbackParams) {
        var request = jQuery.ajax({
            type: "POST", // default = GET,
            url: '/api/' + model + '/',
            data: data,
            contentType: 'application/json',
            success: function (msg) {
                $('#results').text(msg);
                if (callback) // only fire a callback if it has been specified
                    callback(msg, callbackParams);
            },
            error: function (jqXHR, textStatus) {
                alert('Request failed: ' + textStatus);
            }
        });
    }

and data is something like:

{ "_id" : ObjectId("5069f825cd4c1d590cddf206"), "firstName" : "John", "lastName" : "Smith", "city" : "Vancouver", "country" : "Canada" }

My controller will be able to parse it? And next time the data may not match that signature (eg:

{ "_id" : ObjectId("5069f825cd4c1d56677xz6"), "company" : "Acme" }

In my controller, I have tried:

public HttpResponseMessage Post([FromBody]JObject value)

and:

public HttpResponseMessage Post([FromBody]string value)

and (because this is actually to work with a mongo db):

public HttpResponseMessage Post([FromBody]BsonDocument value)

but it looks like the object mapper wants to map to something other than string...

Jonathan
  • 4,916
  • 2
  • 20
  • 37

4 Answers4

26

You can have your post method that takes in a HttpRequestMessage to by pass the model binding logic and you can read the content of the request directly:

    public HttpResponseMessage Post(HttpRequestMessage req)
    {
        var data = req.Content.ReadAsStringAsync().Result; // using .Result here for simplicity...
        ...

    }

By the way, the reason why the action that takes in JObject doesn't work is because of 'ObjectId("...")' that is used as the value of "_id" in your data...

Maggie Ying
  • 10,095
  • 2
  • 33
  • 36
20

We passed json object by jquery, and parse it in dynamic object. it works fine. this is sample code:

ajaxPost:

...
Content-Type: application/json,
data: {
          "name": "Jack", 
          "age": "12"
      }
...

webapi:

[HttpPost]
public string DoJson2(dynamic data)
{
    string name = data.name;
    int age = data.age;

    return name;
}

similary question on stackoverflow: WebAPI Multiple Put/Post parameters

Community
  • 1
  • 1
Bes Ley
  • 1,685
  • 1
  • 20
  • 39
2

In your input, "_id": ObjectId("5069f825cd4c1d590cddf206") is what is breaking the JSON materialization on the server. Removing ObjectId and using "_id" : "5069f825cd4c1d590cddf206" works with JObject as well as Dictionary<string, object>

-6

It is very easy, you just need to put the Accept Header to "application/json".

Javier Ramírez
  • 301
  • 3
  • 4