运维开发网

c# – Web Api返回扩展的键值对象而不是原始的JSON对象

运维开发网 https://www.qedev.com 2020-05-15 09:27 出处:网络 作者:运维开发网整理
当我发送{“name”:“John Doe”,“age”:18,“country”:“USA”}到我的C#Web API,POST到api / test,我将它存储在我的mongo test-collection中并返回更新后的文件: [HttpPost] [Route("{collection}")] public IHttpActionResult Upsert(string collecti
当我发送{“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") };
0

精彩评论

暂无评论...
验证码 换一张
取 消