Web Api returns 扩展 key-value object 而不是原始 JSON object

Web Api returns expanded key-value object instead of original JSON object

当我将 {"name":"John Doe", "age":18, "country":"USA"} 发送到我的 C# Web API 并将 POST 发送到 api/test 时,我将其存储在我的 mongo test 中-collection 和 return 更新后的文档:

[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;
}

这有效,但结果现在是 key-value object:

[
  {
    "_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"
}

我怎样才能做到这一点?

您正在 return 直接 BsonDocument WebAPI 正在尽可能地序列化到 JSON,但不正确。

尝试调用 MongoDB.Bson.BsonExtensionMethods.ToJson 这会将其正确序列化为 JSON ?

然后 return 原始 JSON:

return new HttpResponseMessage { Content = new StringContent(document.ToJson(), System.Text.Encoding.UTF8, "application/json") };

MongoDB.Bson中有一个扩展方法"ToJson",returns您更喜欢json。

您可以在将使用此方法的序列化设置中添加 Converter:

public class BsonDocumentJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(BsonDocument);
    }

    public override bool CanRead
    {
        get
        {
            return false;
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        string json = (value as BsonDocument).ToJson();
        writer.WriteRawValue(json);
    }
}

在您的 WebApiConfig 中添加转换器:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var jsonFormatter = config.Formatters.JsonFormatter;
        var settings = jsonFormatter.SerializerSettings;

        settings.Converters.Add(new BsonDocumentJsonConverter());
    }
}