【发布时间】:2016-03-16 10:40:22
【问题描述】:
当我使用POST 将{"name":"John Doe", "age":18, "country":"USA"} 发送到我的C# Web API 到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"
}
我怎样才能做到这一点?
【问题讨论】:
标签: c# mongodb json.net asp.net-web-api2