本文介绍了MongoDB C# - 如何将任意 JSON 文档保存为动态类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个通用的 Web Api 控制器,它允许我将 JSON 文档保存到集合中,而无需指定 C# 类型.我试图将代码浓缩为基本要素:

I am trying to write a general purpose Web Api controller that will allow me to save a JSON document to a collection WITHOUT specifying a C# type. I've tried to condense the code down to the essentials:

public class PassThroughController : ApiController
{
    [Route("api/mongodb/{collection}")]
    public void Post(string collection, dynamic document)
    {
        const string connectionString = "mongodb://localhost";

        var client = new MongoClient(connectionString);
        var db = client.GetServer().GetDatabase("SampleDb");
        var mongoCollection = db.GetCollection(collection);

        mongoCollection.Save(document,
            new MongoInsertOptions
            {
                WriteConcern = WriteConcern.Acknowledged
            });
        }
}

我正在尝试发布一个简单的文档:

I'm trying to post a simple document:

{ id: "2112", name: "Rush" }

但是无论我向该方法发送什么内容,都会收到与此类似的错误:Save 只能用于具有 Id 的文档."

But no matter what I send to the method, I get an error similar to this: "Save can only be used with documents that have an Id."

我们为 Id(Id、id、_id)尝试了许多不同的属性,但它们都导致了类似的问题.

We've attempted a number of different properties for Id (Id, id, _id) but they all result in a similar issue.

有什么想法吗?

谢谢

推荐答案

在同事的帮助下,我想出了一个解决方案:

With the help of a co-worker, I figured out a solution:

public class PassThroughController : ApiController
{
    [Route("api/mongodb/{collection}")]
    public void Post(string collection, HttpRequestMessage message)
    {
        const string connectionString = "mongodb://localhost";

        var client = new MongoClient(connectionString);
        var db = client.GetServer().GetDatabase("SampleDb");
        var mongoCollection = db.GetCollection(collection);

        var json = message.Content.ReadAsStringAsync().Result;
        var document = BsonSerializer.Deserialize<BsonDocument>(json);

        mongoCollection.Save(document,
            new MongoInsertOptions
            {
                WriteConcern = WriteConcern.Acknowledged
            });
        }
}

这篇关于MongoDB C# - 如何将任意 JSON 文档保存为动态类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 19:28