Skip navigation

Category Archives: ASP.NET WebAPI

Source codes will be put on soon….

ASP.NET Web API Route Debugger

Over the time, I found around one  third of the user questions of Web API is about routing. Such as:


There is no easy way to figure out how the route were decided and eventually everything retrogress into “guessing”.

I was inspired by Haack’s ASP.NET Route Debugger, and decided to build a route debugger for ASP.NET Web API. The tool should visualize the routing mechanism and exposing as much information as possible to help user design their routes easily.

User Instruction


You can install Web API route debugger from NuGet

PM> Install-Package WebApiRouteDebugger

If you don’t want to find the package in NuGet Packages Dialog, please make sure you include the Prerelease packages. The package is still in alpha stage.

Route Simulate Page

The package will create an area, under which all components and views are installed. Run your site, navigate to http://<SiteUrl>/rd (if you’re using IIS Express, it may look like http://localhost:52135/rd).

You will see this page:


Put the URL you want to test and click send.


The results is composed of 5 parts:

  1. The HTTP status code. In above example you see a 200, but if you hit a non-exist resource, you will see a 404.
  2. Route Data: what’s the route template and data parsed from URL.
  3. Route selecting: among all the routes, which one is chosen.
  4. Controller selecting: among all controllers found in assemblies, which one is selected.
  5. Action selecting: for the action on the selected controller, which action is selected and why. The chart visualize the decision making process.

Here’s another example:

GET http://localhost:57887/api/value


Since there is no “Value” controller in the system it hits a 404. You can see the “Controller” value in route data is “Value”. The route is selected. However there is no controller mapped.


In the following post, I’ll discuss a small sample show case how to broadcast WebAPI trace through SignalR.

  • SignalR is an async signaling library for .NET to help build real-time, multiuser interactive web applications. It can be used to push data from server to the client.
  • WebAPI tracing is the feature to track all internal activities in the server and log then to customized trace repository.


User can connect to the server tracing page to get real-time trace updating. To access the information, they need to go through basic authentication.

Persisitent Connection

The core component is an persistent connection. Three actions are overrided:

  • When an connection is made, this connection is added to an unauthenticated group.
  • When an connection is released, it is removed from both authenticated and unauthenticated group. Just in case it is in either of them.
  • When a data is recieved from a connection, this data is expected to be a token string. The token string is used to authenticate the client. Details of the token will be discussed later.
public class TracePersistentConnection : PersistentConnection
    public static readonly string Authenticated = "authenticated";
    public static readonly string Unauthenticated = "unauthenticated";

    protected override Task OnConnectedAsync(IRequest request, string connectionId)
        return Groups.Add(connectionId, Unauthenticated);

protected override Task OnDisconnectAsync(string connectionId)
        return Groups.Remove(connectionId, Authenticated)
                     .ContinueWith(task => Groups.Remove(connectionId, Unauthenticated));

    protected override Task OnReceivedAsync(IRequest request, string connectionId, string data)
        if (ClientTokens.Instance.Exists(data))
            return Groups.Add(connectionId, Authenticated)
                         .ContinueWith(task => Groups.Remove(connectionId, Unauthenticated));
            return base.OnReceivedAsync(request, connectionId, data);

You must notice that there are not codes sending message to clients. That is because sending message is the responsibility of trace writer.

Trace Writer

A trace writer is replace the default implementation through WebAPI’s dependency resolver.

public class TraceWriter : ITraceWriter
    private ConcurrentQueue<TraceRecord> _traces;

    private TraceWriter()
        _traces = new ConcurrentQueue<TraceRecord>();

    private static TraceWriter s_instance = new TraceWriter();

    public static TraceWriter Instance
        get { return s_instance; }

    public void Trace(
        HttpRequestMessage request,
        string category,
        TraceLevel level,
        Action<TraceRecord> traceAction)
        var trace = new TraceRecord(request, category, level);


        var context =
                Status = trace.Status.ToString(),
                Level = trace.Level.ToString(),
                TimeTicks = trace.Timestamp.Ticks,
                Exception = trace.Exception == null ? "" : trace.Exception.Message,

You may notice that when send the trace record to group, I construct a new object  rather than send out the trace it self and let the formatter take care of serialization. I actually tried to do so, but somehow SignalR hit some internal failure and that cause the message never make to the client. I guess it will be my next topic.

Server Setup

Everything is set up in global.asax.cs:

  • Add Route to the WebAPI controller
  • Add Route to the SignalR persistent connection
  • Replace trace writer in dependency resolver
  • Add authentication handler
    public class Global : System.Web.HttpApplication
        protected void Application_Start(object sender, EventArgs e)
            var config = GlobalConfiguration.Configuration;

            config.MessageHandlers.Add(new AuthenticationHandler());

            config.Services.Replace(typeof(ITraceWriter), TraceWriter.Instance);

                new { action = RouteParameter.Optional });

            RouteTable.Routes.MapConnection<TracePersistentConnection>("trace", "trace/{*operatopn}");


The client is a simple HTML + Javascript page.

<html xmlns="">
    <link rel="stylesheet" type="text/css" href="Style/Default.css" />
    <title>WebAPI Tracing + SignalR</title>
    <div id="auth">
        <h1>WebAPI Tracing + SignalR</h1>
        <table id="logTable">
                    <input type="text" id="txtUsername" value="admin" /></td>
                    <input type="password" id="txtPassword" value="password" /></td>
        <input type="button" id="btnLogin" value="Log in" />
        <input type="button" id="btnLogout" value="Log out" />

    <div id="trace">
        <h1>Trace Records</h1>

        <input type="button" id="btnClear" class="button" value="Clear" />

        <div id="message" class="output"></div>
        <div id="exception" class="output"></div>

        <table id="tracetable">
            <tr id="header">
                <th id="requrl">URL</th>
                <th id="level">Level</th>
                <th id="category">Category</th>
                <th id="operator">Operator</th>
                <th id="operation">Operation</th>
                <th id="status">Status</th>

    <script type="text/javascript" src="Scripts/jquery-1.6.4.js"></script>
    <script type="text/javascript" src="Scripts/jquery-ui-1.8.20.js"></script>
    <script type="text/javascript" src="Scripts/jquery.base64.js"></script>
    <script type="text/javascript" src="Scripts/jquery.signalR-0.5.2.js"></script>
    <script type="text/javascript" src="Scripts/Home.js"></script>


$(function () {
    function updateTraceTable(trace) {
        var row = $('<tr></tr>');
        row.append('<td>' + trace.RequestUri + '</td>');
        row.append('<td>' + trace.Level + '</td>');
        row.append('<td>' + trace.Category + '</td>');
        row.append('<td>' + trace.Operator + '</td>');
        row.append('<td>' + trace.Operation + '</td>');
        $('<td>' + trace.Status + '</td>').appendTo(row);


            function () {
                $(this).css("background-color", "lightgreen");
            function () {
                $(this).css("background-color", "white");

    function setupTraceConnection(token) {
        var connection = $.connection('/trace');

        connection.received(function (trace) {

            function () {

        $('#btnClear').click(function () {
            $('#debuginfo').text("clear the trace records");
            $('td', '#tracetable').remove();


    $('#btnLogin').click(function (event) {
        var username = $('input#txtUsername').val();
        var password = $('input#txtPassword').val();

        var options = {
            url: 'api/TraceAuthentication/GetToken',
            type: 'GET',
            data: { 'username': username },
            beforeSend: function (xhr) {
                var raw = username + ":" + password;
                var encoded = jQuery.base64.encode(raw);
                xhr.setRequestHeader("Authorization", "Base " + encoded);
            timeout: '60000',
            success: function (token) {
            error: function (data, status, err) {


Above are the html and the javascript used to update it. Line 26 to 33 of javascript code snippet actually set up the connection to persistent connection. You may wonder what’s the magic string “/trace”. It is the route set up to the PersistentConnection defined in global.asax.cs.

Till now the server is fully functional except one part: security. You don’t want users to see the trace just because they ‘accidentally’ know the endpoint. So here’s the last piece.


Here’s the logic I adopted in this sample:

The client first visit a WebAPI controller to get a token. The controller is protected by basic authentication (or any security model you can image). The token is a security string combing client information and a dynamic server string. The server register the token to a global bag. The client uses the token to send out first message to Hub/PersisitentConnection after connected, which will make itself into an authenticated group, to which Trace information are broadcasted to.

Some of the logic have been already presented in above code snippets.

  • In the TracePersistentConnection, for a new created connection a token is returned.
  • In the TracePersistentConnection, it actively manages the groups.
  • In the client javascript, right after the connection is setup a token is sent to server to announce client’s identity.
  • In the trace writer, the information only writes to the authenticated group.

What missing is a global structure store the tokens.

    public class ClientTokens
        private static ClientTokens s_instnace = new ClientTokens();
        private ConcurrentBag<string> _tokens = new ConcurrentBag<string>();

        private ClientTokens()

        public static ClientTokens Instance
                return s_instnace;

        public bool Exists(string token)
            return _tokens.Contains(token);

        public void AddToken(string token)


I tried to demo following features in this sample:

  • WebAPI and SignalR side by side
  • Broadcast trace in real-time
  • Authentication pattern

Some thing worth to dig deeper:

  • Serialization in SignalR
  • More authentication pattern


There aren’t lots of batching scenario samples out there. The one stands out among them is Brad Wilson’s Batching Handler for ASP.NET Web API. The sample is concise and elegant by leveraging route-specific endpoint handler as well as await async programming model in .net 4.5.

However there is one drawback when you try to customize you own scenario base on this sample, that is if a MessageHandler is added to the configuration, then all the embed request will return a 500 Internal Server Error.


Exception is thrown from HttpClientFactory.CreatePipeline, when it detects that the first MessageHandler (actually all of them) already has InnerHandler property set. What cause the failure is because the HttpConfiguration is reused in an in-memory HttpServer created by BatchHandler. When the in-memory HttpServer is first initialized it tries to re-create the pipeline.

Please note that this issue is tracked by Issue 260 as a known bug. Once it is fixed then you don’t need following mitigation any more.



Here’s my amended sample:

The core solution is to rewrite the Initialize method by deriving a new class from HttpServer.

    public class BatchServer : HttpServer
        private readonly HttpConfiguration _config;

        public BatchServer(HttpConfiguration configuration)
            : base(configuration)
            _config = configuration;

        protected override void Initialize()
            var firstInPipeline = _config.MessageHandlers.FirstOrDefault();
            if (firstInPipeline != null && firstInPipeline.InnerHandler != null)
                InnerHandler = firstInPipeline;

When the BatchingServer is initialized, it detects if the pipeline already exists by looking for first handler and it’s inner handler. Otherwise it call to the base implementation. This log avoid the re-creation issue. The BatchingServer replace  the HttpServer in BatchHandler


In the same project, I created another self-host sample. The initial intention is to use it as a test bed to rapidly verify ideas, however it turns out that under self-host the solution could be very different.

    public class BatchHandler : DelegatingHandler
        private HttpMessageInvoker _server;

        public void SetHandler(HttpMessageHandler handler)
            _server = new HttpMessageInvoker(handler);

        // remaining are the sample implementation

Rather than a configuration, the BatchHandler accepts a MessageHandler. The actual anticipation is an HttpServer.

var config = new HttpSelfHostConfiguration(baseAddress);
config.MessageHandlers.Add(new MarkingMessageHandler());

var batchHandler = new BatchHandler();


    new { id = RouteParameter.Optional });

this.Server = new HttpSelfHostServer(config);


Since user can access to the HttpServer instance, which enables a much simpler solution that is resubmit the request to the HttpServer.

Alternative Mitigation

There is other mitigations which doesn’t involve changes on HttpConfiguration.

  • If submitting the embedded request to the original pipeline is not required, then HttpServer is not required. What you can do is push the embedded request to the separated handler pipeline, which is specifically for embedded requests, and ultimately to the dispatcher. In this solution one particularly important thing is you have to manually add route information to every embedded requests, because these request are created from multi-part content and haven’t gone through HttpServer. They’re so “innocent” that if you don’t so, they will “lost their way” and return 404.
  • Or you can clone the HttpConfiguration, and feed it to a new created HttpServer. To do so, you shall clone all the MessageHandler as well, make sure the InnerHandler are cleaned. This mitigation does not work well if the MessageHandler is not clonable, for example a Singleton-pattern MessageHandler.


  • The root cause of the issue is that HttpServer tries to re-create pipeline based on a reused HttpConfiguration.
  • This issue is known and tracked by Issue 260.
  • Sampling two mitigation solutions under web-host and self-host.