Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

A Beginner's Tutorial on ASP.NET WebApi Hosting(IIS Hosting and Self Hosting)

4.78/5 (22 votes)
27 Dec 2013CPOL4 min read 121.9K   3.2K  
In this article we will look at the various ways of hosting ASP.NET WebApi.

Introduction

In this article we will look at the various ways of hosting ASP.NET WebApi. 

Background

Earlier in one of the articles(A Beginner's Tutorial for Understanding and Implementing ASP.NET Web API[^]), we have seen the basics of WebApi and how can we create a simple WebApi. We have also looked at one single page application that is using WebApi in the backend(A Beginner's Guide for Creating Single Page Applications using Backbone.js and Marionette.js[^]). In both the projects, the WebApi was hosted inside of an ASP.NET application i.e. IIS hosted. If we are developing the WebApi to be consumed from a device application then it is not always necessary to host it as a web application (IIS hosting). In this article we will look at the various ways ASP.NET WebApi can be hosted.

Using the code 

In the first article we have seen the basics of WebApi. We have seen how easy it is to add a WebApi inside an ASP.NET MVC 4 application. When we are using ASP.NET framework to host our WebApi, we are essentially hosting it inside of the IIS. But it is not always required to have an ASP.NET WebApi to host a WebApi. In other words, we need not host our WebApi inside IIS always. In fact, the best part of WebApi(like WCF services) is that it gives us flexibility to host itself in any application.

So there are two ways we can host a WebApi: 

  1. IIS Hosting - Hosting a WebApi inside ASP.NET application.
  2. Self hosting - Have our own application host the ASP.NET WebApi

Let us look at both these methods in detail.

IIS Hosting - Hosting a WebApi inside ASP.NET application

When we host WebApi inside an ASP.NET application the ASP.NET hosting infrastructure takes care of all the hosting needs of the WebApi. If we choose to host our WebApi inside an ASP.NET application there is not much we need to do manually. If we need to create a WebApi that will be hosted inside of the ASP.NET website i.e. IIS, We need to perform following steps.

Create a new ASP.NET MVC4 Project

Image 1 

Note: We can also add the WebApi in an existing ASP.NET MVC 4 application using nuget package manager.

Select the project type as WebApi 

Image 2 

What this will do is that, it will create the routes inside the WebApiConfig as:

C#
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Also, it will create a sample WebApi Controller ValuesController.

C#
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable< string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

Note: I will not create any Api Controller in this article as the main intention of this article is to look at the hosting options. To know more on how to implement the Controllers please refer to the first article.

When we run this application, the web application will be run by the development server and this development server will host the contained WebApi. Let us run the project and test our WebApi using Postman.

Image 3 

On the same lines, once we are done with the development, all we need to do is to host this web application inside IIS and in turn our WebApi will be hosted inside the IIS.

Self hosting - Have our own application host the ASP.NET WebApi

Now when we try to host a WebApi inside of our own application, we need to take care of all the configurations. Since in IIS hosting, all the hosting related configuration is taken from the IIS configuration or the website configuration, we need not do this step. But when we need to self host a WebApi, we need to create our own HttpSelfHostServer server to do the part of IIS and this to provide the configuration, we need to define all the configuration manually.

With that said, Let us try to see how we can have simple console application host a WebApi. For this, the first thing we need to do is to have all the dependent/required packages using the nuget package manager.

 Image 4

Create an object of HttpSelfHostConfiguration class. This will take care of all the configurations needed for our WebApi. Right now let us just configure the URI on which this WebApi will be running.

C#
Uri myUri = new Uri(@"http://localhost:9999");
// Let have our configurations readY
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(myUri); 

The next thing we need to do is to have the route configurations ready and attached to this configuration object. 

C#
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Let us now use the same ValuesController class, we have seen above, to be used as the controller serving the WebApi requests.

C#
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable< string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

Now we have a configuration object ready with some minimal configurations i.e. URI to listen to and the routes. A simple ValuesController ready to serve our requests. Now lets create a an object of HttpSelfHostServer and use the above configuration object with it. We wil then open the server asynchronously.

C#
HttpSelfHostServer server = new HttpSelfHostServer(config);

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

// Wait for it :)
Console.WriteLine("WebApi hosted on " + myUri.AbsoluteUri +" It can be tested now");
Console.ReadLine();

Image 5 

The WebApi is not hosted inside of this console application. Let us go ahead and test this WebApi from Postman.

Image 6 

Point of interest

In this article we have seen how we can host a WebApi inside of IIS (an ASP.NET web application) and how we can self host a WebApi. One Interesting thing could be the use of Open Web Interface for .NET (OWIN) for self hosting the WebApi. This article has been written from a beginner's perspective. I hope this has been informative.

History

  • 27 December 2013: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)