MongoDB is a popular NoSQL database that makes it a great backend for Web APIs which lend themselves towards a document store rather than a relational store. In this blog we show how you can use MongoDB with ASP.NET Web API to build an ApiController with support for HTTP GET, PUT, POST, and DELETE. Our sample controller is a simple contact manager Web API which builds on many of the same concepts as in the tutorial â€œCreating a Web API that Supports CRUD Operationsâ€ so I would recommend that you skim that for background.
In particular, the URI patterns are very similar to that of the tutorial:
|Action||HTTP Method||Relative URI|
|Get a list of all contacts||GET||/api/contacts|
|Get a filtered list of all contacts||GET||/api/contacts?$top=2|
|Get a contacts by ID||GET||/api/contacts/id|
|Create a new contact||POST||/api/contacts|
|Update a contact||PUT||/api/contacts/id|
|Delete a contact||DELETE||/api/contacts/id|
However, there are two differences worth noting:
- We host the sample ApiController in selfhost with a base URI of http://localhost:8080
- We have added support for OData-style queries on GET requests so that you can filter the set of contacts returned using $top, $skip, etc.
But I am getting ahead of myself â€“ letâ€™s get back to building the controllerâ€¦
Note: Please see List of ASP.NET Web API and HttpClient Samples for the complete sample solution. Note that you still have to set up the MongoDB as described in the next section.
As an optional third step once your MongoDB installation has been set up you can use a tool like MongoVUE which allows you to browse and interact directly with the data in a MongoDB database.
Defining the Contact Type
We use the same basic Contact type used in â€œCreating a Web API that Supports CRUD Operationsâ€ but decorate it with an BsonIdAttribute (see the Mongo C# driver reference documentation for details) indicating which field is the id:
Using MongoVUE we can see how Contact instances show up in the MongoDB database. The sample Contact data we use in this sample looks something like this
Defining the Contact Repository
We use the common repository pattern to interact with the backend data source so the next step is to define the shape of the repository. We do this by defining an IContactRepository interface which we then implement so that it targets MongoDB. First, the interface is defined like this:
Implementing the Repository
Itâ€™s when implementing IContactRepository that we use the MongoDB C# driver API to connect to the data and to do the various CRUD operations defined by IContactRepository. First we set up the connection to database and get a Contact collection. By default we use the connection string â€œmongodb://localhost:27017â€ pointing at the localhost database we set up above.
For the purpose of this sample we also reset the database and add some default entries so we have something to start with. Note that the classes MongoServer, MongoDatabase, and MongoCollection<T> are all thread-safe so they can be used simultaneously by separate threads.
We now add the actual CRUD implementations as follows:
Creating the Contact Controller
Thatâ€™s it for the repository so we can now implement the actual ApiController. We base the implementation on the common pattern for supporting GET, PUT, POST, and DELETE as follows:
Note: We use IQueryable<Contact> as the return type of the Get() method. This enables automatic query-support using OData query syntax including $top and $skip. That is, if you use a URI like â€œ/api/contacts?$top=2â€ with a â€œ?$top=2â€ query component then you will only get the first two entries back.
Hosting the Controller
Now that we have the controller we can either host it in ASP or as selfhost. Here we use selfhost to host the controller in a simple console application but it would work exactly the same if hosted in ASP. As usual we create a HttpSelfHostConfiguration, add a route, then create a server, and start it:
Note: In order to successfully start the selfhost server you have to run as admin (or configure http.sys with the appropriate URI prefix using netsh).
Trying out the Controller
When running the controller can be accessed using any HTTP client. In the full sample I show how to use HttpClient to do GET and POST but Fiddler is often very useful for trying out various combinations of GET, PUT, POST, and DELETE by using the Composer tab manually to create requests. For example, you can create a POST request like this to insert a new Contact and then hit Execute:
Similarly you can create a GET request to ask for the two first entries which will yield a result like this where the response body contains the first two Contacts:
As mentioned above, when you modify the data you can track the contents of the MongoDB database using MongoVUE.