CouchDB on .NET 4.5 with Async / Await 10/22/2015

Generics, JSON serialisation and Async/Await make CouchDB a snap from .NET 4.5

Download the source code

Last updated: 10/22/2015

Photo credit: Living room by MoneyBlogNewz


Historically accessing CouchDB from .NET has benefitted from a client library, especially if asynchrony was on your shopping list.  However a big draw card for a client library was to abstract away the HTTP interface.

However with the improvements to System.Net.Http.HttpClient when used with System.Net.Http.Formatting extension methods in .NET 4.5 render client libraries unnecessary.

Wrapping HttpClient with a generic method (Show me the code!)

An assumption of this example is that there is a 1:1 relationship between POCO domain model objects and documents in your database.  To my mind this is not a controversial assumption but may be a deal-breaker in a brown field project.  That said if you are still skilling up on document databases, now would be a good time to make sure there are no Relational model assumptions encoded in your domain model.  A nested assumption is these POCOs will neatly serialise to JSON.

Consider the following method on an class designed to wrap HttpClinet:

Consuming this method with the canonical Customer class would be as follows:

var cust = new Customer();
var response = wrapper.Put<Customer, CreateResponse>(cust);

The implementation of the CreateResponse class in this case would be something like this:

The design here is to create a POCO that the response from CouchDB can be serialised into.  The HTTP API docs specify the JSON structures returned by each method so this is a trivial part of the implementation.

It is then an exercise in variation on a theme to implement other wrapper methods on this class for GET, POST, DELETE and other HTTP methods you will need to talk to the CouchDB HTTP API.


There are a number of authentication options available for CouchDB.  The default and least desirable is the Admin Party.  OAuth is supported but is worthy of serveral posts to itself.  The _session API supports using a cookies for authentication to CouchDB, and is a good choice for many scenarios.

Once you obtain an AuthSession cookie it can be passed with subsequent requests by using HttpClientHandler and CookieContainer as follows:


Those familiar with MVCC mechanism of CouchDB will notice that this sample does not address (apart from a cursory comment) handling Conflict semantics.  Brevity is the first reason for this omission but more to the point it your authors position that managing concurrency exceptions in your app is a higher level architectural decision than is in scope for this example.

I am chipping away at a more comprehensive full stack example for ASP.NET 4.5 which will address architectural concerns.

comments powered by Disqus