我如何/可以将json对象传递给webapi控制器(POST),并且 没有 类可将其映射到,而是将其作为任意内容来处理?
因此,如果我像这样从客户那里传递消息:
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); } }); }
数据是这样的:
{ "_id" : ObjectId("5069f825cd4c1d590cddf206"), "firstName" : "John", "lastName" : "Smith", "city" : "Vancouver", "country" : "Canada" }
我的控制器将能够解析吗?下次数据可能与该签名不匹配(例如:
{ "_id" : ObjectId("5069f825cd4c1d56677xz6"), "company" : "Acme" }
在我的控制器中,我尝试过:
public HttpResponseMessage Post([FromBody]JObject value)
和:
public HttpResponseMessage Post([FromBody]string value)
和(因为这实际上是与mongo数据库一起使用):
public HttpResponseMessage Post([FromBody]BsonDocument value)
但是看起来对象映射器想要映射到字符串以外的其他东西…
您可以让您的post方法接受HttpRequestMessage来传递模型绑定逻辑,并且可以直接读取请求的内容:
public HttpResponseMessage Post(HttpRequestMessage req) { var data = req.Content.ReadAsStringAsync().Result; // using .Result here for simplicity... ... }
顺便说一句,执行JObject的操作不起作用的原因是因为’ObjectId(“ …”)’被用作数据中“ _id”的值…