Self-Hosting in ASP.Net Web API

Introduction

In this article you learn about Self-Host, how we can Self-Host the ASP.NET Web API. In this article, you don't have need of the IIS server. We Host the Web API in a Console application.

Step 1

First we create the console application.

  • Start Visual Studio 2012.
  • Select "New Project" from the Start page.
  • In the Templates, select Installed template->Visual C#.
  • Select "Console application" and change name to "Hosting".
  • Click on the "OK" button.

    shost.jpg

Step 2

Set the ".Net Framework 4".

  • In the "Solution Explorer" right-click on the  project.
  • Select "Properties".
  • In the "Properties windows" Select the ".Net Framework 4" From the Drop Down List of Target Folder.

    shost1.jpg

  • For applying the change open a prompt and click on "Yes".

Step 3

We check that the Nuget Package Manager is installed or not.

  • Go to the Tools menu.
  • If there is a "Library Package Manager" visible then the "Nuget Package Manager" is installed.
  • If "Library Package Manager" is not visible then it is not installed.

For installation of "Nuget Package Manager":

  • Go to the "Tools" menu then select "Extension and Updates".
  • In the "Extension and Updates" dialog box select "Online".
  • In the search box Type "nuget package manager".
  • Select the "Nuget Package Manager and Install it.

Step 4

Now we install the Web API Self-Host Package.

  • Go to the "Tools" menu then select "Library Package Manager" -> "Manages Nuget Packages For Solution".
  • In the "Nuget Package Manager" dialog box type "Microsoft.AspNet.WebApi.SelfHost".

    shost13.jpg

  • Select the ASP.NET Web API Self Host and click Install.

    shost14.jpg

  • Click on the "I Accept" button.

Step 5

Create the Model class:

  • In the "Solution Explorer".
  • Right-click on the project then select "Hosting" -> "Add" -> "Class".
  • Change the name of class as "Item".
  • Click on the "OK" button.

Add this code in the "Item" Class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace Hosting  
  7. {  
  8.     public class Item  
  9.     {  
  10.         public int Id { getset; }  
  11.         public string Name { getset; }  
  12.         public string Category { getset; }  
  13.     }  
  14. }   

Step 6

To add a Controller class:

  • In the "Solution Explorer".
  • Right-click on the project then select "Hosting" -> "Add" -> "Class".
  • Change the name of the class to "ItemsController".
  • Click on the "OK" button.

Add this code in the "ItemsController" class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Text;  
  6. using System.Web.Http;  
  7. namespace Hosting  
  8. {  
  9.     public class ItemsController : ApiController  
  10.     {  
  11.         Item[] items = new Item[]    
  12.         {   
  13.             new Item { Id = 1, Name = "Apple", Category = "Fruit" },   
  14.             new Item{ Id = 2, Name = "Tomato", Category = "vasitable" },   
  15.             new Item{ Id = 3, Name = "T-Shirt", Category = "cloths" }   
  16.         };  
  17.         public IEnumerable<Item> GetAllItems()  
  18.         {  
  19.             return items;  
  20.         }  
  21.         public Item GetItemById(int id)  
  22.         {  
  23.             var item = items.FirstOrDefault((i) => i.Id == id);  
  24.             if (item == null)  
  25.             {  
  26.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  27.             }  
  28.             return item;  
  29.         }  
  30.         public IEnumerable<Item> GetItemsByCategory(string category)  
  31.         {  
  32.             return items.Where(i => string.Equals(i.Category, category,  
  33.                     StringComparison.OrdinalIgnoreCase));  
  34.         }  
  35.     }  
  36. } 

Step 7

Now we Host our Web API.

Open the "Program.cs" file and add this code into this file:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Web.Http;  
  7. using System.Web.Http.SelfHost;  
  8. namespace Hosting  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             var config = new HttpSelfHostConfiguration("http://localhost:8080");  
  15.             config.Routes.MapHttpRoute(  
  16.                 "API Default""api/{controller}/{id}",  
  17.                 new { id = RouteParameter.Optional });  
  18.             using (HttpSelfHostServer server = new HttpSelfHostServer(config))  
  19.             {  
  20.                 server.OpenAsync().Wait();  
  21.                 Console.WriteLine("Press Enter to quit.");  
  22.                 Console.ReadLine();  
  23.             }  
  24.         }  
  25.     }  
  26. }   

Step 8

Add a new project in this application using the following:

  • In the "Solution Explorer".
  • Right-click on project then select "Add" -> "New Project"
  • Change the name to "Client".

    shost6.jpg

Step 9

Install the "Microsoft ASP.NET Web API Client Library" using the following:

  • Go to the "Tools" menu then select "Extension and Updates".
  • In the "Extension and Updates" dialog box select "Online".
  • In the search box type "Microsoft.AspNet.WebApi.Client".
  • Select the "Microsoft ASP.NET Web API library" and install it.

    shost15.jpg

Step 10

Add the reference of the client to the "Hosting" project using the following:

  • In the "Solution Explorer" right-click on the "Client" project.
  • Select "Add reference".
  • Open a "Reference" dialog box.
  • Select the solution and choose "Projects".

    shost8.jpg

  • Click on the "Ok" button.

Step 11

Open the "Program.cs" file in the "Client" project.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Net.Http;  
  7. namespace Client  
  8. {  
  9.     class Program  
  10.     {  
  11.         static HttpClient client = new HttpClient();  
  12.         static void Main(string[] args)  
  13.         {  
  14.             client.BaseAddress = new Uri("http://localhost:8080");  
  15.             ListAllItems();  
  16.             ListItem(1);  
  17.             ListItems("fruit");  
  18.             Console.WriteLine("Press Enter to quit.");  
  19.             Console.ReadLine();  
  20.         }  
  21.         static void ListAllItems()  
  22.         {  
  23.             HttpResponseMessage resp = client.GetAsync("api/items").Result;  
  24.             //resp.EnsureSuccessStatusCode();  
  25.             var items = resp.Content.ReadAsAsync<IEnumerable<Hosting.Item>>().Result;  
  26.             foreach (var i in items)  
  27.             {  
  28.                 Console.WriteLine("{0} {1} {2}", i.Id, i.Name,  i.Category);  
  29.             }  
  30.         }  
  31.         static void ListItem(int id)  
  32.         {  
  33.             var resp = client.GetAsync(string.Format("api/products/{0}", id)).Result;  
  34.             //resp.EnsureSuccessStatusCode();  
  35.             var item = resp.Content.ReadAsAsync<Hosting.Item>().Result;  
  36.             Console.WriteLine("ID {0}: {1}", id, item.Name);  
  37.         }  
  38.         static void ListItems(string category)  
  39.         {  
  40.             Console.WriteLine("items in '{0}':", category);  
  41.             string query = string.Format("api/items?category={0}", category);  
  42.             var resp = client.GetAsync(query).Result;  
  43.             resp.EnsureSuccessStatusCode();  
  44.             var items = resp.Content.ReadAsAsync<IEnumerable<Hosting.Item>>().Result;  
  45.             foreach (var item in items)  
  46.             {  
  47.                 Console.WriteLine(item.Name);  
  48.             }  
  49.         }  
  50.     }  
  51. }   

Step 12

Now execute the application.

  • In the "Solution Explorer" right-click on the "Hosting" Project.
  • And select "set as Start up project".

    host12.jpg
  • Press F5 for execution.

    shost10.jpg

Step 13

Debug the project "Hosting" using the following:

  • In the Solution Explorer" right-click on the project "Client".
  • Select "Debug"-> "Start new instance".

    shost16.jpg
Output
 
shost12.jpg


Recommended Ebook

Diving Into ASP.NET WebAPI

Download Now!
Similar Articles