ASP.NET Web API: in-memory hosting

One of the nice features in the new ASP.NET Web API is in-memory hosting, i.e., the possibility to directly connect a HttpClient to the server-side runtime, without any network usage or HTTP message serialization:

var config = new HttpConfiguration();
config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });
// additional config ...
var server = new HttpServer(config);
var client = new HttpClient(server);
var r = client.GetAsync("")

In the above code, notice how the HttpClient is initialized with the HttpServer, establishing the direct client-server connection.

This feature is relevant on integration or end-to-end testing scenarios, by decreasing the time required for a round-trip and avoiding the self-hosting complexity (e.g. URI access control).

This feature also illustrates an interesting symmetry between the client and server stacks, around the message handler concept, as described in the following paragraphs.

Server side

The last post described the ASP.NET Web API server-side processing architecture : what happens since a HTTP request is received until a response is produced.

As stated in that post, this processing architecture is composed by three layers: hosting, message handler pipeline and controller handling. The hosting layer

  • translates HTTP requests, received from lower level APIs, into HttpRequestMessage instances;
  • pushes this messages into the above message handler pipeline, wrapped by a HttpServer.  Typically, at the end of this pipeline there is an handler that dispatches the messages to the chosen controller.

Of special relevance is the fact that HttpServer derives from HttpMessageHandler (composite pattern).

Client side

The architecture of the new HttpClient class was also described in a previous post, namely the fact that the HttpClient internally uses a HttpMessageHandler to compute the HTTP response, given the HTTP request.



It is this symmetry – HttpServer is a message handler and HttpClient receives a message handler – that allows the direct connection of the client to the server, bypassing the server side hosting layer, as showed in the following diagram.



Nice, isn’t it?

5 thoughts on “ASP.NET Web API: in-memory hosting

  1. SeriousM

    i just tried this way but i cant get it to work.
    would you mind to provide a sample project for this?
    best regards!

  2. Pingback: ASP.NET Web API integration testing with in-memory hosting | StrathWeb

  3. Pingback: Distributed Weekly 159 — Scott Banwart's Blog

  4. Pingback: Doing unit and integration tests with the Web API HttpClient | Pablo Cibraro's blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s