Different ways of hosting ASP.NET Web API

Sheonarayan
Posted by in ASP.NET Web API category on for Advance level | Points: 250 | Views : 3443 red flag
Rating: 5 out of 5  
 3 vote(s)

In this article, we shall learn two ways of hosting ASP.NET Web API Project. First is Self hosting using OWN and other is hosting on IIS as a normal web project. We are going to learn both of them in this article.
Recommendation
Read Routing in ASP.NET Web API - An Introduction before this article.

Introduction

This post is an effort to answer the Forums question asked about ways of hosting ASP.NET Web API. There are two ways to host the ASP.NET Web API application
  1. Self-hosting (using OWIN in ASP.NET API 2 onwards)
  2. IIS hosting (hosting as an web application)

Those who are not familiar with ASP.Web API can learn ASP.NET Web API tutorials here

ASP.NET Web API Self-hosting 

Older version of ASP.NET Web API (version < 2) can be self hosted using "Microsoft ASP.NET Web API Self Host". At the time of writing this article, the version of ASP.NET Web API is 2 so we will learn the latest techniques of hosting ASP.NET Web API.

Currently, ASP.NET Web API can be self hosted using OWIN (Open Web Interface for .NET). 

What is OWIN?
OWIN (Open Web Interface for .NET) defines an abstraction between .NET web server and web applications, It decouples the web application from the server that is why OWIN is good for self-hosting any kind of web application.

Using OWIN to self-host ASP.NET Web 2


Step 1 - create console application

Create a new console application project in Visual Studio as shown in the picture below.



Step 2 - add reference to the OWIN self-host packages
Add the reference of ASP.NET Web  API and OWIN self-host packages using NuGet Package Manager. Right click console application project and select "Manage NuGet Packages ...".

Write "OwinSelfHost" in the search box at the top-right and press Enter key. You should be getting the result like below. Click on Install button to install the necessary packages to self-host ASP.NET Web API.


After successfully installing the ASP.NET Web API OWN Self-host packages, the solution explorer should look like following



Step 3 - add Startup class to route the API urls
Now add a new class file named "Startup.cs" in the project by right clicking and copy-paste below code snippet.

Below code snippet set the HTTP configuration of the application in the same way as we normally specify in the RouteConfig.cs file of normal ASP.NET Web API project. Learn more about ASP.NET Routing here.This simply says that how a http request should be treated in this application.

using System;
using System.Web.Http;

namespace APISelfHosting
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate : "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }                
                );
            appBuilder.UseWebApi(config);
        }
    }
}
So, when any request comes to this application starting with "api" followed by API controller name defined in the project, the Web API behavior starts.
Step 4 - configure the start of ASP.NET Web API application 
Now copy-paste the following code in the Program.cs file of the project.

When the console application starts, this Main method executes and it sets the base HTTP URL of the Web API project to "http://localhost:1579/" and write the response back to the client based on which API controller method is being called.

using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;

namespace APISelfHosting
{
    public class Program
    {
        static void Main(string[] args)
        {
            string baseUrl = "http://localhost:1579/"; // change based on your domain setting

            using (WebApp.Start<Startup>(url: baseUrl))
            {
                HttpClient client = new HttpClient();
                var resp = client.GetAsync(baseUrl).Result;

                Console.WriteLine(resp);
                Console.WriteLine(resp.Content.ReadAsStringAsync().Result);

                Console.ReadLine();
            }

            Console.ReadKey();
        }
    }
}

That's it, the self-host related configurations are all set. 
Step 5 - creating controller to test
Now to test, we simply need to create few controllers. Let's create a API controller named "DefaultAPIController" and copy-paste following code.

Notice that we have written 3 methods and returns some strings. In real time, we can change these methods to what we require to return from the ASP.NET Web API.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace APISelfHosting
{
    public class DefaultAPIController : ApiController
    {
        // GET api/MathAPI
        public IEnumerable<string> Get()
        {
            return new string[] { "DotNetFunda", "TechFunda", "ITFunda" };
        }

        // GET api/MathAPI/19
        public string Get(int id)
        {
            return "The vlaue is: " + id;
        }

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

        }

        // similarly create other methods
    }
}
Step 6 - Time to test
After creating a test controller, it is time to run the Console application project, hit Start from the toolbar in Visual Studio and if all above steps are followed, following screen should appear that says that the current request of "http://localhost:1579/" url doesn't have anything (so 404 error) as we have not set anything to the root of the application. Our API is configured to "/api/{controllerName}"





No worries, keep the application running and open a browser and write following url in the browser address bar.
  1. http://localhost:1579/api/DefaultAPI/  and the response should be 

    <ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <string>DotNetFunda</string>
    <string>TechFunda</string>
    <string>ITFunda</string>
    </ArrayOfstring>



  2. http://localhost:1579/api/DefaultAPI/50 and the response should be 

    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">The vlaue is: 50</string>

ASP.NET Web API IIS Hosting

Hosting ASP.NET Web API on IIS is as simple as hosting any other ASP.NET web application on IIS. Here is an article written by me on How to host asp.net application on the web server (IIS), read this and follow the steps and you should be done.


Thanks for reading the article, if you liked the article do not forget to share to friends or colleagues. Also subscribe to RSS feed to get the new article notification in your email.
Recommendation
Read Learn how to bind a Google Chart with WebGrid in Web API2 after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Kumarkrishna184 on: 12/20/2015 | Points: 25
Thanks Sir....
Posted by: Rajayadav on: 12/21/2015 | Points: 25
Nice Sir, thanks for sharing
Posted by: Rajayadav on: 12/24/2015 | Points: 25
Nice Sir, Thanks for sharing

Login to post response

Comment using Facebook(Author doesn't get notification)