Self-Host with Web API

By Ugo Lattanzi on July 16th , 2012 in WebAPI WebDev | comments

Share On Google Share On Facebook Share On Twitter

Inside Web API there is a hidden gem that isn't having the right interest, the Self-Host. The most typical mistake is to consider Web API as part of ASP.NET MVC. Really it doesn't and there aren't shared libraries between them.

 

In fact you can use Web API without ASP.NET MVC simply installing it from NuGet. The first advantage to be separated from MVC is the Self-Host.

What does it mean Self-Host in Web API?

The answer is really simple; you can “start” the application without use IIS or IIS Express and, for this scenario, there are two important aspects:

How can we do that?

Like previous, the answer is really simple. We need to create a console application and a few lines of code. The first step is to create new project from Visual Studio, choose Console Application and then install the Web API package:

Now, as for the web application, we have to create a folder for our controllers and put inside the classic ValuesController:

public class ValuesController : ApiController
{
  public IEnumerable<string> Get()
  {
    return new[]
             {
               "http://tostring.it",
             "http://imperugo.tostring.it",
             "http://twitter.com/imperugo",
             "http://www.linkedin.com/in/imperugo"
             };
  }
}

Right now we have to create only the host for the server, so:

using System;
using System.Web.Http;
using System.Web.Http.SelfHost;


namespace imperugo.webapi.selfhost
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:12345");

        config.Routes.MapHttpRoute(&quot;Default&quot;, &quot;{controller}&quot;, new {controller = &quot;Home&quot;});

        // Create server
        var server = new HttpSelfHostServer(config);

        // Start the server
        server.OpenAsync().Wait();

        Console.WriteLine(&quot;WebServer Started&quot;);
        Console.WriteLine(&quot;Press enter to exit&quot;);
        Console.ReadLine();
    }
}

}

Absolutely easy and fun.

You can download this sample cloning my spike repository from github http://s.tostring.it/Q1wt6U