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

ASP.NET Core(.NET8)中如何让MongoDB使用JsonPropertyAttribute?

让MongoDB使用JsonPropertyAttribute映射属性名称

不需要给每个属性额外添加[BsonElement],可以通过自定义MongoDB序列化约定来复用[JsonProperty]的配置,具体步骤如下:

1. 创建自定义序列化约定类

这个类会读取属性上的JsonPropertyAttribute,并将其指定的名称设置为MongoDB文档的字段名:

using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using Newtonsoft.Json;

public class JsonPropertyConvention : IMemberMapConvention
{
    // 约定名称,可自定义
    public string Name => "JsonPropertyConvention";

    public void Apply(BsonMemberMap memberMap)
    {
        // 读取当前属性上的JsonPropertyAttribute
        var jsonPropAttr = memberMap.MemberInfo
            .GetCustomAttributes(typeof(JsonPropertyAttribute), true)
            .FirstOrDefault() as JsonPropertyAttribute;

        // 如果存在有效属性名,就设置为MongoDB字段名
        if (jsonPropAttr != null && !string.IsNullOrWhiteSpace(jsonPropAttr.PropertyName))
        {
            memberMap.SetElementName(jsonPropAttr.PropertyName);
        }
    }
}

2. 在应用启动时注册约定

在Program.cs(或Startup类的配置逻辑中)注册这个自定义约定,让MongoDB驱动全局生效:

// 创建约定包并添加自定义约定
var conventionPack = new ConventionPack();
conventionPack.Add(new JsonPropertyConvention());

// 注册约定,t => true 表示对所有类型生效
ConventionRegistry.Register("JsonPropertyConventions", conventionPack, t => true);

补充:适配System.Text.Json的情况

如果你用的是System.Text.Json的[JsonPropertyName]而非Newtonsoft.Json的[JsonProperty],只需修改自定义约定类中的属性类型:

using System.Text.Json.Serialization;

// ... 其他代码不变
var jsonPropAttr = memberMap.MemberInfo
    .GetCustomAttributes(typeof(JsonPropertyNameAttribute), true)
    .FirstOrDefault() as JsonPropertyNameAttribute;

if (jsonPropAttr != null && !string.IsNullOrWhiteSpace(jsonPropAttr.Name))
{
    memberMap.SetElementName(jsonPropAttr.Name);
}

这样配置后,你的模型属性上的JsonProperty(或JsonPropertyName)属性就会被MongoDB驱动识别,自动映射为对应的文档字段名,无需重复添加[BsonElement]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:15:03