I am trying to write a general purpose Web Api controller that will allow me to save a JSON document to a collection WITHOUT specifying a C# type. I\'ve tried to condense the co
With the help of a co-worker, I figured out a solution:
public class PassThroughController : ApiController
{
[Route("api/mongodb/{collection}")]
public void Post(string collection, HttpRequestMessage message)
{
const string connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var db = client.GetServer().GetDatabase("SampleDb");
var mongoCollection = db.GetCollection(collection);
var json = message.Content.ReadAsStringAsync().Result;
var document = BsonSerializer.Deserialize(json);
mongoCollection.Save(document,
new MongoInsertOptions
{
WriteConcern = WriteConcern.Acknowledged
});
}
}