Web API Hosting:

In this section, you will learn how to host a Web API.

The Web API application can be hosted in two ways.

  1. IIS Hosting
  2. Self Hosting

IIS Hosting:

Web API can be hosted under IIS, in the same way as a web application. You have learned to create a Web API in the previous section. As you have seen there, a Web API is created with ASP.NET MVC project by default. So, when you host your MVC web application under IIS it will also host Web API that uses the same base address.

Self Hosting:

You can host a Web API as separate process than ASP.NET. It means you can host a Web API in console application or windows service or OWIN or any other process that is managed by .NET framework.

You need to do following steps in order to self-host a web API.

  1. Use HttpConfiguration to configure a Web API
  2. Create HttpServer and start listening to incoming http requests

Let's see how to host a simple Web API in console application.

First of all, create a console project in Visual Studio 2012 for Desktop (or latter version).

Note: You must open Visual Studio in Administration mode.

Create Console Application

Now, you need to add Microsoft ASP.NET Web API 2.x Self Host package using NuGet. Right click on project in the Solution Explorer window and select Manage NuGet Packges..

Open NuGet Manager

In the Manage NuGet Packages window, select Online option in left pan and search for web-api. This will list all the packages for Web API. Now, look for Microsoft ASP.NET Web API 2.2 Self Host package and click Install.

Install Web API Self Host Package

Click on Accept button in the License Acceptance window.

Accept License Agreement

This will install the package into your project.

Install Web API self Hosting Package

Now write the following code in the Main() method of Program class.

Example: Self-Hosting Web API

class Program
{
    static void Main(string[] args)
    {

        var config = new HttpSelfHostConfiguration("http://localhost:1234");

        var server = new HttpSelfHostServer(config, new MyWebAPIMessageHandler());
        var task = server.OpenAsync();
        task.Wait();

        Console.WriteLine("Web API Server has started at http://localhost:1234");
        Console.ReadLine();
    }
}

In the above code, first we created an object of HttpSelfHostConfiguration class by passing uri location. Then, we created an object of HttpSelfHostServer by passing config and HttpMessageHandler object. And then we started listening for incoming request by calling server.OpenAsync() method. This will listen requests asynchronously, so it will return Task object.

Create MyWebAPIMessageHandler class and write the following code.

Example: MessageHandler

class MyWebAPIMessageHandler : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var task = new Task<HttpResponseMessage>(() => {
            var resMsg = new HttpResponseMessage();
            resMsg.Content = new StringContent("Hello World!");
            return resMsg;
        });

        task.Start();
        return task;
    }
}

Thus, you can create simple console application and host simple Web API that returns "Hello World!" to every request.

Run the console application using Ctrl + F5.

Run Console Application

Open web browser and enter http://localhost:1234/ and see the result.

Response in Browser

Hosting Controller Infrastructure:

You can use the same ASP.NET routing and ApiController capabilities of ASP.NET Hosting in self hosting.

In the same self hosting console application, create simple HomeController class as shown below.

Example: Web API Controller

public class HomeController : ApiController
{
    public string Get() {
        return "Hello World!";
    }

    public string Get(string name) {
        return "Hello " + name;
    }
}

Now, in the Main() method, configure a default route using config object as shown below.

Example: Self Hosting Web API

static void Main(string[] args)
{

    var config = new HttpSelfHostConfiguration("http://localhost:1234");
    config.Routes.MapHttpRoute("default",
                                "api/{controller}/{id}",
                                new { controller = "Home", id = RouteParameter.Optional });

    var server = new HttpSelfHostServer(config);            
    var task = server.OpenAsync();
    task.Wait();

    Console.WriteLine("Web API Server has started at http://localhost:1234");
    Console.ReadLine();
}

Please notice that we removed an object of MessageHandler when creating an object of HttpSelfHostServer.

Now, run the console application by pressing Ctrl + F5. Open the browser and enter http://localhost:1234/api or http://localhost:1234/api?name=steve and see the result as shown below.

Web API Response