1

我对 ASP.NET MCV 4 和 Mongo DB 相当陌生,并试图构建 Web API。我以为我终于做对了,但是当我启动应用程序并输入:http://localhost:50491/api/document进入我的浏览器时,我收到此错误消息

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

这是我的代码

这是文档类

public class Document
{
    [BsonId]
    public ObjectId DocumentID { get; set; }

    public IList<string> allDocs { get; set; }
}

这是连接到数据库的地方:

public class MongoConnectionHelper
{
    public MongoCollection<BsonDocument> collection { get; private set; }

    public MongoConnectionHelper()
    {
        string connectionString = "mongodb://127.0.0.1";
        var server = MongoServer.Create(connectionString);

        if (server.State == MongoServerState.Disconnected)
        {
            server.Connect();
        }

        var conn = server.GetDatabase("cord");

        collection = conn.GetCollection("Mappings");  
    }

这是 ApiController 类:

public class DocumentController : ApiController
{
    public readonly MongoConnectionHelper docs;

    public DocumentController()
    {
        docs = new MongoConnectionHelper();
    }

    public IList<BsonDocument> getAllDocs()
    {
        var alldocs = (docs.collection.FindAll().ToList());
        return alldocs;

    }

}

我进一步阅读并提示错误消息:

Type 'MongoDB.Bson.BsonObjectId' with data contract name 'BsonObjectId:http://schemas.datacontract.org/2004/07/MongoDB.Bson' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

这一切都很好,但我该怎么做呢?

4

2 回答 2

2

a) 不要通过 Web API 序列化您的文档类,并创建一些要序列化的 DTO,或者 b) 使用其他东西作为 ID。

如果您想要一个简单的自动生成 ID,并且您可以接受它会占用更多空间的事实,您可以诉诸以下“hack”:

public class Document
{
    public Document()
    {
        Id = ObjectId.GenerateNewId().ToString();
    }

    public string Id { get; set; }
}

这样,您将获得 MongoID,但它们将存储为字符串。

于 2013-01-10T13:29:44.157 回答
0

如果您需要 XML 格式的 Web API2 响应,您需要像下面这样处理默认 ID

例如:ObjectId("507f191e810c19729de860ea")

您需要从序列化中删除 Id。

[DataContract]
public class Document
{
    [BsonId]
    public string Id { get; set; }
    [DataMember]
    public string Title { get; set; } //other properties you use
}

或者您可以使用自定义逻辑更改 ID 的类型

public class GuidIdGenerator : IIdGenerator
{
    public object GenerateId(object container, object document)
    {
        return  Guid.NewGuid();
    }

    public bool IsEmpty(object id)
    {
        return string.IsNullOrEmpty(id.ToString());
    }
}

public class Document
{
    [BsonId(IdGenerator = typeof(GuidIdGenerator))]
    public string Id { get; set; }
    public string Title { get; set; } //other properties you use
}
于 2017-08-04T07:29:11.127 回答