Creating Your Own Host for a Web API Service

Kevin Rattan has done several posts on Microsoft’s ASP.NET Web API (you can find all of this blog’s Web API posts here) which have done a great job of showing (among other things) how the Web API is different from WCF. The Web API is designed from the ground up to leverage the HTTP protocol, for instance, which makes it easy to create RESTful services. But, like WCF, it’s ridiculously easy to add a Web API controller to either an ASP.NET or ASP.NET MVC application. And, also, like WCF you can create your own host for your Web API services.

Which, of course, raises the question: If it’s so easy to add a Web API service to a website why would you want to create your own host? Hosting your own Web API services is obviously a niche solution: most of the time you’ll want to leverage IIS as your service’s host. However, creating your own host allows you to control  your service in ways that might be difficult to implement if your service is part of a website hosted by IIS. For instance, with your own host the URL for your service is completely under your control (well, except for the server’s name) and isn’t constrained by the name of the website the service is part of. Managing your host is also independent of IIS management: You may want to self-host because you find that working with your Web Administrator is even less fun than working with your DBA–creating your own Web API host lets you bypass that person.

Configuring the Host Project

If you are going to create your own host, you should create the host as a Windows Service. That isn’t essential: practically any .NET project type can be used to host a Web API service. If you wanted your host to have a user interface that you could interact with then creating your host as a WPF or WinForms project would meet that goal more easily than a Windows Service project would. However, creating your host as a Windows Service is easy to do (as long as you don’t need the UI) and allows you to manage your host from the Services node in the Windows Management Console. For instance, by setting your Windows Service’s start mode as Automatic, your host will start up with the computer it’s running on and shut down with it.

The first step in creating your Web API host is to create a new Windows Service project in Visual Studio (File | New | Project | Windows | Windows Service).  Once the project is created, right mouse click on it in Solution Explorer and select Manage NuGet Packages to retrieve the Web API package  you need. Once in NuGet, search in the online section for “aspnet.webapi” to find all (and only) the Web API packages. From the packages listed, the one that you need so that you can create your own host is called Microsoft ASP.NET Web API Self Host (do not select Microsoft ASP.NET Web API Web Host). Click on the package, click the Install button, accept the licensing terms and you project is almost ready to write some code–there’s just two things left to do before you can start writing code.

First, add a reference to System.Web.Routing to your project–you’ll need this later to configure your service. You’ll also want your service to have a more meaningful name than the default Service1. Delete the default Service1 in your project, right-mouse click on your project in Solution Explorer, and select Add | New Item | General | Windows Service. Give your service a meaningful name (I used “PHVService”) and click the Add button. Now you’re ready to write code.

Writing the Windows Service

A Windows Service initially displays the Service’s graphical designer which you can ignore–open its code file by double clicking on the designer. There are two key events in a Windows Service’s life: when it starts and when it stops. The methods associated with these events (OnStart and OnStop) are, typically, where you’ll want to load your host and where you’ll want to shut your host down. I’m going to create my host in the OnStart event and shut it down in the OnStep event (for the following code to work, you’ll need to add using statements for System.Web.Http.SelfHost and System.Web.Http to Service’s code file). Since that means that my HttpSelfHostServer must be available in both methods, I declare it at the class level:

 partial class PHVService : ServiceBase
  private HttpSelfHostServer shs;

First, create an HttpSelfHostConfiguration object that will specify how your service behaves. When you instantiate the HttpSelfHostConfiguration object pass it the endpoint for your service (the initial part of the endpoint will have to be the name of the computer that your service is running on–the rest is up to you):

 protected override void OnStart(string[] args)
  HttpSelfHostConfiguration hcfg =
    new HttpSelfHostConfiguration("");

The configuration object gives you the ability to configure a great many things about your service–all but one of which is optional. You must set up a route to the controller that makes up your service. This example sets up the simplest possible route (“”) and ties it to a controller called CustomerManagementController:

                         new { controller = "CustomerManagement" });

Finally, you’ll want to open your host. Create your HttpSelfHostServer, passing your configuration object,and then call the host’s OpenAsync method:

shs = new HttpSelfHostServer(hcfg);

The OnStop method is simpler. When the service is shut down (as part of the server shutting down, for instance) this method will be called automatically. In the OnStop method, you want to call the HttpSelfHostServer object’s CloseAsync method to start shutting down your host. However, I don’t think it would be a good practice to let the service continue to the end of its OnStop method until your host really has shut down. So, in this code, I’ve used the Await method to hold execution until the CloseAysnc method completes (I also call the host’s Dispose method just to free up any remaining resources that the host might be controlling):

protected override void OnStop()

There’s still stuff to do. It’s still your responsibility to create the Web API controller referenced in the route you created. You should also create a setup project you can use to install your Windows Service on its server. And, of course, while I’ve shown you how to create your own host, I haven’t shown you how you can configure your Web API service. That’s another post.

Learning Tree has an excellent course about creating services in .NET that covers the ASP.NET Web API: WCF and Web API .NET Services: A Comprehensive Hands-On Introduction.

Peter Vogel

Type to search

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.