You need to enable JavaScript to run this app. 如何在ASP.NET Core 5控制器中实现BSON格式数据返回
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core 5控制器中实现BSON格式数据返回

ASP.NET Core 5 启用BSON返回的解决方案

问题根因

你遇到的500错误核心由两个常见问题导致:

  1. 旧版WebAPIContrib.Core.Bson包仅适配.NET Core 2.x/3.x,在.NET 5下存在类型兼容问题
  2. BSON规范默认要求顶级序列化节点必须是文档(键值对结构对象),你直接返回List<string>数组作为根节点,不符合默认序列化规则

修复步骤

1. 安装适配.NET 5的依赖包

卸载原有旧版WebAPIContrib.Core.Bson,安装2.3.0及以上适配.NET 5的版本:

Install-Package WebAPIContrib.Core.Bson -Version 2.3.0

2. 注册BSON格式化器

在ConfigureServices中添加如下配置,确保内容协商规则正确:

services.AddControllers()
    .AddBsonSerializerFormatters(options =>
    {
        options.SupportedMediaTypes.Add("application/bson");
    });

// 补充内容协商配置,避免默认返回JSON
services.Configure<MvcOptions>(options =>
{
    options.RespectBrowserAcceptHeader = true;
    options.ReturnHttpNotAcceptable = true;
});

3. 调整接口返回值(核心修复500错误)

将接口返回值包装为对象结构,符合BSON顶级节点要求:

// 通用BSON响应包装类
public class BsonResult<T>
{
    public T Data { get; set; }
}

[HttpGet]
[Route("api/GetList")]
public BsonResult<List<string>> GetList()
{
    return new BsonResult<List<string>>
    {
        Data = new List<string> { "Item1", "Item2", "Item3", "Item4" }
    };
}

4. 调用端验证

请求头添加Accept: application/bson即可正常获取BSON格式响应。
如果确实需要直接返回数组作为根节点,可自定义BSON输出格式化器,绕过顶级文档限制,核心实现逻辑如下:

public class ArraySupportBsonFormatter : BsonOutputFormatter
{
    public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
    {
        if (context.Object is IEnumerable enumerable && context.ObjectType != typeof(string))
        {
            var bsonData = MongoDB.Bson.BsonArray.Create(enumerable).ToBson();
            await context.HttpContext.Response.Body.WriteAsync(bsonData);
            return;
        }
        await base.WriteResponseBodyAsync(context);
    }
}

注册自定义格式化器即可生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 19:45:03