Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.78/5 (22 votes)
26 Dec 2013CPOL4 min read 119.8K   3.2K   50   9
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)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
QuestionHTTP Error 500.19 - Internal Server Error Pin
kwokwah25-Nov-16 21:59
kwokwah25-Nov-16 21:59 
Questionjgrid by kk kodoth Pin
Member 1192586027-May-16 9:22
Member 1192586027-May-16 9:22 
QuestionA Beginner's Tutorial on ASP.NET WebApi Hosting(IIS Hosting and Self Hosting) Pin
JamesHayden2-Nov-15 18:23
JamesHayden2-Nov-15 18:23 
QuestionGood one Pin
KK Kod17-Jul-15 6:49
KK Kod17-Jul-15 6:49 
QuestionReally Dumb!!! Pin
Member 832697023-Jun-15 8:29
Member 832697023-Jun-15 8:29 
Question[My vote of 2] Not of much service to beginners, possibly counter productive! Pin
Member 115917904-May-15 4:54
Member 115917904-May-15 4:54 
SuggestionThanks for the article! Pin
morzel5-Sep-14 20:59
morzel5-Sep-14 20:59 
AnswerArticle of the Day on Microsoft's site Pin
Rahul Rajat Singh27-Jan-14 17:15
professionalRahul Rajat Singh27-Jan-14 17:15 
GeneralMy vote of 1 Pin
pflketan23-Jan-14 23:15
pflketan23-Jan-14 23:15 
Poor

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.