Web API错误无法序列化响应正文

时间:2013-01-10 12:08:50

标签: asp.net mongodb rest mongodb-.net-driver nosql

我是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; }
}

这是与DB的连接:

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.

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

2 个答案:

答案 0 :(得分:2)

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

如果你想要一个简单的自动生成ID,并且你可以消耗更多的空间,你可以采用以下“hack”:

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

    public string Id { get; set; }
}

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

答案 1 :(得分: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
}