I’m working on an API in ASP.NET MVC 4, I’m using MongoDB as a backend.
Due to MongoDB storing and returning BSON objects, and MVC4 returning JSON objects, I figured that it would be rather easy to simply return the BSON on the rest calls.
This didn’t work, so I found the .toJson() method on th BsonDocument class, converts the BSON object to a JSON-string representation. Unfortunately when I return this string through my ApiController, MVC apparently thinks it should re-serialize the string as JSON, which the browser can’t interpret.
So I would like to ask if there is a way to disable the JSON serialization for a specific ApiController method?
My current workaround is to de-serialize the JSON returned from .toJson() before returning it such that it will be serialized again, but this seems rather wasteful.
Presumably you have a schema associated with your application and the resource your api controller is attempting to return. By forcing it to use json, you are ignoring many of the benefits of the WebApi by completely sidestepping content negotiation. What if your client wants xml or yaml or …
The issue you are experiencing is that WebApi doesn’t know how to serialize a BsonDocument. So, you could write a ModelBinder for it such that it knows how to deal with it. Alternatively, and alluding to my first paragraph, create strongly typed entity/resource classes and since both MongoDB and WebApi already know about these types, they’ll be able to work with them natively.