Search code examples
asp.netmongodbrestmongodb-.net-drivernosql

Web API error failed to serialize the response body


Im fairly new to ASP.NET MCV 4 as well as Mongo DB and trying to build web API. I thought I had finally got it right but when I start the app and enter: http://localhost:50491/api/document into my browser I get this error message

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

Here is my code

This is the Document Class

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

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

This is where the Connection to the DB is made:

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");  
    }

Here is the ApiController Class:

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;

    }

}

I read futher on and the error message suggested:

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.

That is all good and well but how do I do that?


Solution

  • Either a) don't serialize your document classes over Web API, and create some DTOs meant to be serialized, or b) use something else as ID.

    If you want an easy auto-generated ID, and you're OK with the fact that it will consume slightly more space, you can resort to the following "hack":

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

    This way, you'll get MongoIDs, but they'll be stored as a string.