【发布时间】:2023-02-07 15:17:45
【问题描述】:
我有一个 ASP.NET API 来处理进入 Mongo 数据库的数据。我还需要为一些文档发送一些动态/不规则数据,这些数据会有一些额外的属性。
我正在尝试使用官方教程中的this code,但是我收到了这个错误
Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonBoolean'.
这是模型类的代码:
public class Incident
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
[BsonElement("Name")]
public string? Name { get; set; }
[BsonExtraElements]
public BsonDocument? ExtraElements { get; set; }
}
这是控制器代码
[ApiController]
[Route("api/[controller]")]
public class IncidentController : ControllerBase
{
private readonly IncidentService _incidentService;
public IncidentController(IncidentService incidentService)
{
_incidentService = incidentService;
}
[HttpGet]
public async Task<List<Incident>> Get() =>
await _incidentService.GetAllIncidents();
}
还有服务
public async Task<List<Incident>> GetAllIncidents() =>
await _incidents.Find(new BsonDocument()).ToListAsync();
奇怪的是,在我实际执行操作之前,崩溃也发生在 POST 中的 Swagger 中。
【问题讨论】:
-
什么是
_incidents?是MongoCollection<Incident>类型吗?同时我认为await _incidents.Find().ToListAsync();而不是await _incidents.Find(new BsonDocument()).ToListAsync();如果没有过滤器,则不需要new BsonDocument()的提供。虽然标题和问题中的错误消息不同。 -
即使发布错误是相同的,只是它也会使 Swagger 崩溃,这是可以预料的
标签: c# asp.net mongodb asp.net-web-api bson