Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

c# - how to post arbitrary json object to webapi

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...