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

MongoDB使用BsonDecimal128时出现类型转换异常及Swagger卡顿问题求助

解决MongoDB BsonDecimal128序列化/反序列化的类型转换错误

问题根源

这个InvalidCastException本质是.NET MongoDB驱动或Swagger的JSON序列化组件,在处理BsonDecimal128类型时出现了类型不匹配:要么实体类属性类型与数据库存储类型映射错误,要么序列化组件无法识别BsonDecimal128,导致错误尝试将其转为布尔值。

具体解决方案

  • 规范实体类属性类型
    优先使用.NET原生decimal类型映射MongoDB的Decimal128,驱动会自动完成双向转换,避免手动处理BsonDecimal128带来的适配问题。

    public class YourEntity
    {
        public ObjectId Id { get; set; }
        public decimal TargetDecimalField { get; set; } // 自动映射为MongoDB的Decimal128
    }
    
  • 配置MongoDB驱动序列化规则
    如果必须使用BsonDecimal128类型,需在驱动初始化时明确序列化配置,强制将decimal类型序列化为Decimal128:

    var clientSettings = MongoClientSettings.FromConnectionString("你的MongoDB连接字符串");
    clientSettings.SerializerRegistry = BsonSerializerRegistry.Create(new BsonSerializerConfiguration
    {
        Serializers = { new DecimalSerializer(BsonType.Decimal128) }
    });
    var mongoClient = new MongoClient(clientSettings);
    
  • 修复Swagger的JSON序列化适配
    Swagger默认的JSON序列化组件(如Newtonsoft.Json)无法识别BsonDecimal128,需添加自定义转换器:

    public class BsonDecimal128Converter : JsonConverter<BsonDecimal128>
    {
        public override BsonDecimal128 ReadJson(JsonReader reader, Type objectType, BsonDecimal128 existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            if (reader.Value is decimal decimalVal)
            {
                return new BsonDecimal128(decimalVal);
            }
            throw new JsonSerializationException("无法将值转换为BsonDecimal128");
        }
    
        public override void WriteJson(JsonWriter writer, BsonDecimal128 value, JsonSerializer serializer)
        {
            writer.WriteValue(value.ToDecimal());
        }
    }
    

    然后在Swagger配置中注册该转换器:

    services.AddControllers()
        .AddNewtonsoftJson(options =>
        {
            options.SerializerSettings.Converters.Add(new BsonDecimal128Converter());
        });
    
  • 排查查询语句的语法错误
    检查API请求或Shell查询中的过滤、排序条件,确认没有将Decimal128字段误当作布尔值处理(比如错误使用{ targetField: true }这类条件),这类语法会触发驱动的错误类型转换。

  • 验证修复效果
    先用Postman直接调用API验证排序和返回结果是否正常,再通过Swagger UI测试,确认卡顿和类型转换错误是否消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:22:37