Sunday, March 31, 2013

Self-host ASP.NET Web API and SignalR together

A few days ago, I wanted to build a Windows service providing some services via ASP.NET Web API. This was done easily. I just used the HttpSelfHostServer, and everything was fine.

But then I wanted also to inform the clients about some internal changes in my program in an asynchronous way. For this I thought ASP.NET SignalR would be the perfect solution. But unfortunately, SignalR expects an OWIN host, not the HttpSelfHostServer.

Then I spent some time with googling. And finally I was able to find the solution. I had to add the following NuGet packages to my project:


All packages are in pre-release state (version 0.21.0-pre at the moment). But they work already. To fire up the OWIN host, I needed only the following few lines of code:

const string serverUrl = "http://localhost:8080";
using (WebApplication.Start<Startup>(serverUrl))

The configuration itself is done in the Startup class:

public class Startup
 public void Configuration(IAppBuilder app)
  // Configure WebApi
  var config = new HttpConfiguration();
   "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });

  // Configure SignalR

Quite easy if you know it...