当我发送{“name”:“John Doe”,“age”:18,“country”:“USA”}到我的C#Web API,POST到api / test,我将它存储在我的mongo test-collection中并返回更新后的文件:
[HttpPost] [Route("{collection}")] public IHttpActionResult Upsert(string collection, HttpRequestMessage request) { var document = request.Content.ReadAsStringAsync().Result; var doc = BsonDocument.Parse(document); var result = new Db(collection).Upsert(doc).Result; return Ok(result); }
.
public async Task<BsonDocument> Upsert(BsonDocument document) { if (document.Contains("_id")) { await _collection.ReplaceOneAsync(w => w["_id"] == document["_id"], document); } else { await _collection.InsertOneAsync(document); } return document; }
这有效,但结果现在是一个键值对象:
[ { "_name": "_id", "_value": "56e9364d942e1f287805e170" }, { "_name": "name", "_value": "John Doe" }, { "_name": "age", "_value": 18 }, { "_name": "country", "_value": "USA" } ]
我期望的是:
{ "_id": "56e9364d942e1f287805e170", "name":"John Doe", "age":18, "country":"USA" }
我怎样才能做到这一点?
您将直接返回一个BsonDocument,其中WebAPI尽可能最好地序列化为JSON,但不正确.尝试调用MongoDB.Bson.BsonExtensionMethods.ToJson,它会将它正确地序列化为JSON吗?
并返回原始JSON:
return new HttpResponseMessage { Content = new StringContent(document.ToJson(), System.Text.Encoding.UTF8, "application/json") };
精彩评论