Getting Started With ASP.Net Web API 2 : Day 10


Before reading this article, I highly recommend reading the previous parts:

In this article, we will learn about the Self-Host ASP.NET Web API. Without IIS we are able to run our Web API using the Web API self-hosting capabilities.

To make the run a self-hosted ASP.NET Web API, we need to create an instance of a HttpSelfHostConfiguration and pass it into an instance of HttpSelfHostServer, that will create the WCF channel stack responsible for the HTTP interaction of our Web API service.

The following is a code sample to show the Self-Hosting Web API: 

  1. var address = "http://localhost:1234";  
  2.            var congig = new HttpSelfHostConfiguration(address);  
  3.            congig.MapHttpAttributeRoutes();  
  4.            server.OpenAsync().Wait();  
  5.            Console.WriteLine("server running at {0}. Press any key to exit", address);  
  6.            Console.ReadLine();  

The Web API is self-hosting, using a Windows Communication Foundation, that is available on: 

NuGet: Install-Package Microsoft.AspNet.WebApi.SelfHost

As we know that the first version of the Web API also supports the self-hosted mode that is on HttpListener and allows us to run Web API services outside of ASP.NET. We can turn any .NET application into a Web API server, as long as it meets the following requirements:

  • Assigns a specific port, meaning that the URL and port had been reserved for the application with the relevant netsh command. or administrator privileges.
  • Now it would will be able to reference and utilize the WCF components that the Web API self-host is built on, such as System.ServiceModel.

ASP.NET Web API 2 self-hosts using the WCF channel stack layer for getting request messages from the underlying HTTP infrastructure. HttpSelfHostServer sets up an HttpBinding that is configured using the data provided through HttpSelfHostConfiguration, then the HttpBinding is used to configure a WCF message channel stack that is responsible for the communication with the operating system's networking stack. This is the common logic behind the self host.

To run the application using the administrator's mode is the best idea, and if not, then use the netsh tool to reserve a URL for a specific user account.

This is the way we can add a URL and remove a URL.

  • Add a URL: 
    netsh http add urlacl url=http://+:1234/ user=domian\username
  • Remove a URL: 
    netsh http delete urlacl url=http://+:1234/

At application startup, HttpListener tries to register a URL to be able to receive HTTP requests.

Now let's start to develop a slef hosted application using the console based template.


The following things are needed when developing a Web API 2 application for the Self-Host Web API.

Visual Studio 2013

Getting Started

In this section we will follow some important procedures and these are:

  • Create Console Application
  • Add a class file for student
  • Add a class for ApiController.

Step 1

Open the Visual Studio 2013 and click New Project.

Step 2

Select the Console based application and provide a nice name for the project.


Step 3

Add a class named student and use a property. 

  1. using System.ComponentModel.DataAnnotations;  
  2. namespace SelfHosting  
  3. {  
  4.    public class Student  
  5.     {  
  6.        [Required]  
  7.         public int Id { getset; }  
  8.         public string Name { getset; }  
  10.     }  
  11. }  
Step 4

The following is a procedure to install the self-host namespace using the NuGet Package Manager. 
  • Right-click on the Project Name and choose "Manage NuGet Packeges..." as you see in the the following image.


  • Search "selfhost" packeges and we will see a list of selfHost packages. Select Microsoft ASP.NET Web API 2.2 Self Host.


  • Click to Install.


  • After installation we will get a prompt for " I Accept".


    Then we will see the complete installation.


Step 5

Add a Controller class that is inherits from the ApiController class using the System.Web.Http namespace.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using System.Web.Http;  
  9. namespace SelfHosting  
  10. {  
  11.     public class StudentController: ApiController  
  12.     {  
  13.         private static List<Student> stud = new List<Student>{  
  14.             new Student{Id=1, Name="Rajeev"},  
  15.             new Student{Id=2, Name="Ranjan"}  
  16.         };  
  17.         [Route("student")]  
  18.         public IEnumerable<Student> Get()  
  19.         {  
  20.             return stud;  
  21.         }  
  22.         [Route("student/{id:int}",Name="StudentById")]  
  23.         public Student GetById(int id)  
  24.         {  
  25.             var studen = stud.FirstOrDefault(x => x.Id == id);  
  26.             if (studen == nullthrow new HttpResponseException(HttpStatusCode.NotFound);  
  27.             return studen;  
  28.         }  
  29.         [Route("student")]  
  30.         public IHttpActionResult Post(Student s)  
  31.         {  
  32.             stud.Add(s);  
  33.             return CreatedAtRoute("StudentById"new { id = s.Id }, s);  
  34.         }  
  36.     }  
  37. }  
Step 5

In this section we will simply start the server and get the data (student records) in JSON format using the web API controller and without IIS. 
  1. using System;  
  2. using System.Net.Http;  
  3. using System.Text;  
  4. using System.Threading.Tasks;  
  5. using System.Web.Http;  
  6. using System.Web.Http.SelfHost;  
  7. namespace SelfHosting  
  8. {  
  9.     class Program  
  10.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             var address = "http://localhost:1234";  
  15.             var congig = new HttpSelfHostConfiguration(address);  
  16.             congig.MapHttpAttributeRoutes();  
  17.             using (var server = new HttpSelfHostServer(congig))  
  18.             {  
  19.                 //server.OpenAsync().Wait();  
  20.                 server.OpenAsync().Wait();  
  21.                 Console.WriteLine("server running at {0}. Press any key to exit", address);  
  22.                 var client = new HttpClient()  
  23.                 {  
  24.                     BaseAddress = new Uri(address)  
  25.                 };  
  26.                 var students = client.GetAsync("student").Result;  
  27.                 Console.WriteLine(students.Content.ReadAsStringAsync().Result);  
  28.                 var newStudent = new Student { Id = 3, Name = "Nisa" };  
  29.                 var response = client.PostAsJsonAsync("student", newStudent).Result;  
  31.                 if (response.IsSuccessStatusCode)  
  32.                 {  
  33.                     var student3 = client.GetAsync("student/3").Result;  
  34.                     Console.WriteLine(student3.Content.ReadAsStringAsync().Result);  
  35.                 }  
  36.                 Console.ReadLine();  
  37.             }  
  39.         }  
  40.     }  
  41. }  


Further Reading

Getting Started with ASP.NET Web API 2 : Day 11

Similar Articles