MiniProfiler with WebApi

Over the past few months at Koan, whilst building Seg, we have been moving towards a Knockout frontend, powered by WebAPI 2. Everything has gone well, with one hiccup. MiniProfiler hasn’t been playing nice.

It seems that WebAPI is sending response headers, before Application_EndRequest is being called, which is why when MiniProfiler tries to add the X-MiniProfiler-Ids header when MiniProfiler.Stop() is called, an exception is being thrown telling us that headers cannot be added after they have already been sent to the client. Obviously.

The solution to this seems to be (and is working for us), to create a DelegatingHandler, (Michael Lumpp wrote an enlightening piece that helped me out) that can ‘stop’ MiniProfiler before the response is sent.

Just add the new DelegatingHandler to your HttpConfiguration, and you’re good to go.

public class MiniProfilerMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = base.SendAsync(request, cancellationToken);

        MiniProfiler.Stop();

        return response;
    }
}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.MessageHandlers.Add(new MiniProfilerMessageHandler());
    }
}