ASP.NET Web API is a framework for building HTTP services that can reach a broad range of clients including browsers, phones and tablets. ASP.NET Web API ships with ASP.NET MVC 4 and is part of the Microsoft web platform. However, this does not mean that you are limited to hosting your web APIs in IIS! ASP.NET Web API gives you the flexiblity to host your web APIs anywhere you would like, including self-hosting in your own process.

Note: This sample uses the NuGet package restore feature to install the required set of NuGet packages when the sample is first built. Make sure you have network access to the public NuGet feed on www.nuget.org before building this sample the first time.

To self-host a web API you first need to setup your server configuration. At a minimum you need to specify the base address for your HTTP server and configure routes for your web APIs. Note that you configure your routes just like you would using ASP.NET Routing, except the routes need to be added to the route collection on your config instance

C#
Edit|Remove
// Set up server configuration 
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress); 
 
config.Routes.MapHttpRoute( 
    name: "DefaultApi", 
    routeTemplate: "api/{controller}/{id}", 
    defaults: new { id = RouteParameter.Optional } 
);

Implement your web API just like you would if it was web hosted by deriving from ApiController and adding your actions. Here we add a simple HelloController with a Get action that returns a simple string:

C#
Edit|Remove
public class HelloController : ApiController 
{ 
    public string Get() 
    { 
        return "Hello, world!"; 
    } 
}
 
Create a self-host server with this configuration and open the server to start listening for requests. You will need to run the sample as an administrator to be able to open the server: 
C#
Edit|Remove
// Create server 
server = new HttpSelfHostServer(config); 
 
// Start listening 
server.OpenAsync().Wait(); 
Console.WriteLine("Listening on " + _baseAddress);
 Lastly, create an HttpClien and send a GET request to the web API to retrieve the string:
C#
Edit|Remove
// Call the web API and display the result 
HttpClient client = new HttpClient(); 
client.GetStringAsync(_address).ContinueWith( 
    getTask => 
    { 
        if (getTask.IsCanceled) 
        { 
            Console.WriteLine("Request was canceled"); 
        } 
        else if (getTask.IsFaulted) 
        { 
            Console.WriteLine("Request failed: {0}", getTask.Exception); 
        } 
        else 
        { 
            Console.WriteLine("Client received: {0}", getTask.Result); 
        } 
    });

When you run the application you should see the result displayed:

 

More Information

ASP.NET Web API home page
Tutorial: Self-host a Web API