Click here to Skip to main content
Click here to Skip to main content

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

, 27 Dec 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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

 

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 

 

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

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

Also, it will create a sample WebApi Controller ValuesController.

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.

 

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.

 

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.

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. 

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.

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.

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();

 

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

 

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)

Share

About the Author

Rahul Rajat Singh
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[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
SuggestionThanks for the article! Pinmembermorzel5-Sep-14 21:59 
AnswerArticle of the Day on Microsoft's site PinmvpRahul Rajat Singh27-Jan-14 18:15 
GeneralMy vote of 1 Pinmemberpflketan24-Jan-14 0:15 
Poor

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 27 Dec 2013
Article Copyright 2013 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid