You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用MongoDB C# Driver原样保存Postman复杂JSON请求体?

用MongoDB C# Driver原样存储复杂JSON请求体的简单方案

针对你遇到的复杂JSON请求体无法原样存入MongoDB的问题,以下是几种直接可行的实现方案:

方案1:直接接收原始JSON字符串并转BsonDocument

这是最可靠的方式,完全保留原始JSON的结构和类型信息:

using MongoDB.Bson;
using MongoDB.Driver;

public async Task SaveRawJson(string rawJson)
{
    var mongoClient = new MongoClient("mongodb://localhost:27017");
    var db = mongoClient.GetDatabase("YourDatabaseName");
    var collection = db.GetCollection<BsonDocument>("YourCollectionName");

    // 直接将JSON字符串解析为BsonDocument,原样存入
    var bsonDocument = BsonDocument.Parse(rawJson);
    await collection.InsertOneAsync(bsonDocument);
}

在Web API接口中,可通过流读取原始请求体:

[HttpPost]
public async Task<IActionResult> PostRawJson()
{
    using var reader = new StreamReader(Request.Body);
    var rawJson = await reader.ReadToEndAsync();
    await SaveRawJson(rawJson);
    return Ok();
}

方案2:用dynamic类型接收请求体并转换

如果习惯模型绑定,可直接用dynamic接收请求体,再转成BsonDocument:

using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;

[ApiController]
[Route("api/store")]
public class JsonStoreController : ControllerBase
{
    private readonly IMongoCollection<BsonDocument> _collection;

    public JsonStoreController(IMongoClient mongoClient)
    {
        var db = mongoClient.GetDatabase("YourDatabaseName");
        _collection = db.GetCollection<BsonDocument>("YourCollectionName");
    }

    [HttpPost]
    public async Task<IActionResult> StoreJson([FromBody] dynamic requestBody)
    {
        var bsonDoc = BsonDocument.Parse(requestBody.ToString());
        await _collection.InsertOneAsync(bsonDoc);
        return Ok();
    }
}

方案3:修复JsonElement/JsonDocument的序列化问题

如果坚持要用JsonElement或JsonDocument,需注册对应的MongoDB序列化器,避免空对象问题:

// 在Program.cs/Startup.cs中全局注册序列化器
using MongoDB.Bson.Serialization;
using System.Text.Json;

BsonSerializer.RegisterSerializer(new JsonElementSerializer());
BsonSerializer.RegisterSerializer(new JsonDocumentSerializer());

// 存储方法示例
public async Task SaveJsonElement(JsonElement jsonElement)
{
    var mongoClient = new MongoClient("mongodb://localhost:27017");
    var db = mongoClient.GetDatabase("YourDatabaseName");
    var collection = db.GetCollection<JsonElement>("YourCollectionName");

    await collection.InsertOneAsync(jsonElement);
}

注意事项

  • 确保使用最新稳定版MongoDB C# Driver(当前推荐2.20.x及以上)
  • 请求的Content-Type必须设置为application/json
  • 存储后可通过MongoDB Compass直接验证文档结构是否与原始JSON一致

内容的提问来源于stack exchange,提问作者Asana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 16:45:00