Unit test Web Api methods with in-memory HttpServer

Here are the steps to test your Web Api methods with an in-memory webserver. We have a simple Web Api project with 1 method:
/api/test returns "hello".

This unit test method can be used in Web API v1. In Web Api v2 there are some other methods (with Owin).

  • Add new class project
  • Add a reference to the Web Api project to be tested
  • Iin the Nuget package window: install-package nunit (or install your favorite unit tester)
  • install-package Microsoft.AspNet.WebApi -version 4.0.30506.0
  • Add reference to System.Web.dll
  • Add a new Class with Unit test code:

    public class UnitTest
        public void Test()
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { routetemplate = "Version", id = RouteParameter.Optional });

            var server = new HttpServer(config);
            var client = new HttpClient(server);

            // act
            var response = client.GetAsync("http://server/api/test").Result;

            Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
            var answer= response.Content.ReadAsStringAsync().Result;

In this test a HttpServer is started with the same configuration as the Web Api project, and a HttpClient is created. After that, a request is fired and the response
is analysed.
And the test should work🙂 However I had some issues to get this working, in the response there was always a HTPP 404 not found result. This is solved by calling in the test first some method of the Web Api project (for example the configuration object).

January 15, 2014 Posted by | Uncategorized | 5 Comments

Create PDF’s with ASP.NET Web Api

This blog describes how to generate PDF’s with ASP.NET Web Api using PdfSharp/MigraDoc.


Sample result:

http://servername/api/test.pdf?author=bert generates a pdf with  the authorname as parameter. This sample can be extended to create

complete dynamically  reports.


Sample code is available on


Step 1: Generate new empty ASP.NET project with Visual Studio


Step 2: Install Microsoft.AspNet.WebApi from NuGet


Step 3: Install ‘PDFsharp-MigraDoc-GDI’ from NuGet:



Step 4: Change web.config

Add the following to in web.config file in the system.webServer section:


<modules runAllManagedModulesForAllRequests="true"/>


This is needed because otherwise the IIS webserver will search for a static PDF file and not a dynamic one generated by ASP.NET.


Step 5: Add global.asax with the following content:


    public class Global : System.Web.HttpApplication
        public static void RegisterRoutes(RouteCollection routes)

                name: "IdWithExt",
                routeTemplate: "api/{controller}.{ext}");

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

        protected void Application_Start(object sender, EventArgs e)

            var pdfFormatter = new PdfMediaTypeFormatter();

In the Global.asax we register the PDF Mediatypeformatter, defined in the next step.


Step 6: Add a Mediatype formatter for PDF 

Add a new class ‘PdfMediaTypeFormatter’. This class overrides from MediaTypeFormatter. Important is the ‘SupportedType’, only controllers

who return the SupportedType will use this formatter. Another important parameter is the ‘object value’ in the WriteToStreamAsync method. This parameter

contains the specified PDF parameter (in our case the author name).


   public class PdfMediaTypeFormatter : MediaTypeFormatter
       private static readonly Type SupportedType = typeof(Person); 

       public PdfMediaTypeFormatter()
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/pdf"));
            MediaTypeMappings.Add(new UriPathExtensionMapping("pdf", "application/pdf"));

       public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
           var taskSource = new TaskCompletionSource<object>(); 
               var person = (Person)value; 

               var doc = PdfGenerator.CreatePdf(person.Name); 
               var ms = new MemoryStream();

                doc.Save(ms, false); 

               var bytes = ms.ToArray();
                writeStream.Write(bytes, 0, bytes.Length);
           catch (Exception e)
           return taskSource.Task;

       public override bool CanReadType(Type type)
           return SupportedType == type;

       public override bool CanWriteType(Type type)
           return SupportedType == type;

Step 7:  Add a simple test controller class.



This controller returns a Person class, which will be rendered using the PDF Media Type.

    public class TestController:ApiController
        public HttpResponseMessage GetTest(string author)
            var person=new Person{Name=author};
            return Request.CreateResponse(HttpStatusCode.OK,person);

Step 8: Add a Person class

    public class Person
        public String Name { get; set; }

Step 9: Add code to generate a PDF (class PdfGenerator).


This code creates an in-memory PDF and returns it.


    public static class PdfGenerator
        public static PdfDocument CreatePdf(string author)
            var document = new Document();
            var sec = document.Sections.AddSection();
            sec.AddParagraph("Author:" + author);
            return RenderDocument(document);

        private static PdfDocument RenderDocument(Document document)
            var rend = new PdfDocumentRenderer {Document = document};
            return rend.PdfDocument;


Step 10: Test!

Run the project and open http://localhost:64118/api/test.pdf?author=piet

A PDF file with the specified authorname will be returned if all goes well



October 1, 2013 Posted by | Uncategorized | , , | 8 Comments

Consuming webservices with Portable Class Library (PCL)

This a sample to consume a webservice using Portable Class Library (PCL). In this sample we are retrieving some geographical information from the site. Because we use portable class libraries, we can reuse this code on the different .NET platforms: Silverlight, .NET Framework 4.5, Windows Phone 7.5/8 and Windows 8 Store Apps.

Support for PCL is coming for platforms like Mono, Xamarin.iOS and Xamarin.Android. Write once, run everywhere!


Step 1/5: Create Portable Class Library project in Visual Studio 2012

File –> New-> Project –> Visual C# –> Portable Class Library

Be sure to select .NET Framework 4.5:



Set target frameworks as follows:



Step 2/5: Install nuget packages

In the NuGet package manager console type:

1: ‘install-package –pre’ : installs the PCL version of HttpClient

Result should be (without license text):

PM> install-package -pre

Attempting to resolve dependency ‘Microsoft.Bcl (≥ 1.0.16-rc)’.

Attempting to resolve dependency ‘Microsoft.Bcl.Build (≥ 1.0.0-rc)’.

Successfully installed ‘Microsoft.Bcl.Build 1.0.0-rc’.

Successfully installed ‘Microsoft.Bcl 1.0.16-rc’.

Successfully installed ‘Microsoft.Net.Http 2.1.3-beta’.

Successfully added ‘Microsoft.Bcl.Build 1.0.0-rc’ to PortableClassLibrary4.

Successfully added ‘Microsoft.Bcl 1.0.16-rc’ to PortableClassLibrary4.

Successfully added ‘Microsoft.Net.Http 2.1.3-beta’ to PortableClassLibrary4.


2: ‘install-package newtonsoft.json – pre’: installs the PCL version of JSON.NET




Step 3/5: Write some code in the PCL

In this sample we are retrieving some information about earthquakes:

Copy the json result of the earthquakes in a new c# file. Use paste –> paste special –> paste JSON as classes.



Results should be:

Geonames models


Now write the code to request the webservice and parse the results:

GeoNames Webservice Client Api


public Earthquake[] GetEarthquakes() {

var client = new HttpClient();

client.BaseAddress = new Uri(;

var response = client.GetAsync("earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt").Result;

var earthquakesJson = response.Content.ReadAsStringAsync().Result;

var rootobject = JsonConvert.DeserializeObject<Rootobject>(earthquakesJson);

return rootobject.earthquakes;



Step 4/5:  Add a Windows 8 client

Add a Windows 8 client to the solution

Solution-> Add new Project… –> Windows Store –>  Blank App Xaml

Add a reference to the portable class library:

Select Project –> add reference –> select the new portable class library


Step 5/5: Add 1 line of code to the Windows 8 client

Open the mainpage.xaml.cs file and add to the OnNavigatedTo method:

var earthquakes = new GeonamesApi().GetEarthquakes();

if everything works ok, there will be some earthquakes coming back. Or there are no earthquakes in this area Glimlach . Otherwise inspect with

Fiddler to see whats going on.



Next step is to put the results somewhere in the user interface but I’ll leave that for another post. Good candidate for this is the MVVM Cross Library:



March 19, 2013 Posted by | Uncategorized | 8 Comments

TypeScript and JQuery example

This is an example of using TypeScript and JQuery.


1] Install TypeScript from here:

2] Create typescript file hello.ts:

see typescript file

3] Get a JQuery TypeScript definition
file jquery.d.ts, for example here:

4] Compile to javascript
using command tsc:

tsc hello.tsc

5] Inspect javascript file
A javascript file hello.js is generated

see javascript file

6] Create html page
Now we can use the javascript in a html page:

see html file

7] Result
Result should be: ‘hallo bert’

Complete code:

January 6, 2013 Posted by | Uncategorized | 3 Comments

State of the map in Sarajevo

Bing Maps:


Google Maps:




April 4, 2012 Posted by | Uncategorized | Leave a comment

test windows 8 Einde seizoen dreigt voor Sulejmani | | Het laatste nieuws het eerst op

March 5, 2012 Posted by | Uncategorized | Leave a comment

Cloud9Ide Hello Soep Soep

Hello Soep Soep in


November 2, 2011 Posted by | Uncategorized | Leave a comment

Node.js hello world on Windows

1] Download node.exe
Default installation: C:\Program Files\nodejs

2] Write helloworld.js javascript file:

var http = require(‘http’);  
http.createServer(function (req, res) {  
  res.writeHead(200, {‘Content-Type’: ‘text/plain’});  
  res.end(‘Hello World\n’);  
}).listen(8124, "");  
console.log(‘Server running at’);

3] Run
(In dos): Run node.exe helloworld.js

Console should be saying: ‘Server running at’

4] Call from browser

Voila an other hello world!

More info:

October 19, 2011 Posted by | Uncategorized | Leave a comment

Hello world PhoneGap on Windows Phone 7


September 19, 2011 Posted by | Uncategorized | Leave a comment


Coding tip of the day: when you have two lists of strings and want to know the items that are in the first list, but not in the second, use IList.Except:

var firstlist = new List<string>() { "soep", "aap" };

var secondlist = new List<string>() { "soep", "koffie" };

var result = firstlist.Except(secondlist).ToList();

This code returns a list of strings with one item: “aap”

May 18, 2011 Posted by | Uncategorized | 1 Comment


Get every new post delivered to your Inbox.