c# – Web Api返回扩展的键值对象而不是原始的JSON对象
发布时间:2020-12-15 23:31:44 所属栏目:百科 来源:网络整理
导读:当我发送{“name”:“John Doe”,“age”:18,“country”:“USA”}到我的C#Web API,POST到api / test,我将它存储在我的mongo test-collection中并返回更新后的文件: [HttpPost][Route("{collection}")]public IHttpActionResult Upsert(string collectio
当我发送{“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") }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |