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:

Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.HttpListener
Microsoft.Owin.Hosting

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))
{
 Thread.Sleep(Timeout.Infinite);
}

The configuration itself is done in the Startup class:

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

  // Configure SignalR
  app.MapHubs();
 }
}

Quite easy if you know it...

4 comments:

  1. Hi, Interesting, I need to do the same I think. I have a ASP.NET Web API that serves an ExtJS client and also a Windows Services that process long running tasks. Both I need to keep my client updated for some tasks. Is that what you are talking about? Thanks

    ReplyDelete
  2. Hi Alex,
    I am not 100% sure if I understand you right, but if you want to use your Windows service also to host Web Api as well as SignalR, this works without problems.
    BTW: Since some months it has left beta status, so it's much more reliable to use it in between.
    Happy coding
    Markus

    ReplyDelete
  3. I like this website a lot, Its a very nice post to read and find information about Self-host ASP.NET. I'm keen of learning more and more aobut ASP.NET, So if you post more about it, then it'll be so nice of you.

    OptiMized360 - Best Healthcare Websites Company America.

    ReplyDelete