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

Introduction

In this article we will learn how to host an ASP.NET Web API in a console application, using the Open Web Interface for .NET (OWIN) to self-host the Web API framework.

OWIN defines the abstraction between .NET web servers and web applications. In a general scenario the OWIN decouples with the web application from the server, that makes OWIN as a self-hosting a web application for our own process, that is absent of IIS.

Before the start of OWIN Self Hosting applications let's try to understand self hosting using my old article. According to this article we will be able to understand the basics of Self Hosting.

Now we are able to start learning the OWIN self hosting application step-by-step.

Step 1

Create a Console Application.

To create a Console application we need to use a basic procedure. Click on the File menu and choose New, then click Project. After getting the project we need to specify the language from the Installed Templates, so we will choose Visual C#, and click Windows and then click Console Application. Now we can provide a nice name for the application.

OwinProject

Step 2

Add the Web API and OWIN Packages

There are two ways to install the OWIN package using the Nuget Package manager. First we need to only right-click on the Project from the Solution Explorer and select the NuGet Package Manager and search the OWIN self-host package. We will be able to see many applications listed below. In those we need to select the appropriate package. Secondly we need to click on the Tools menu,  then click Library Package Manager, then click Package Manager Console. In the Package Manager Console window, enter the following command:

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

According to this command we will able to install the WebAPI OWIN selfhost package and all the required OWIN packages.

PackagesOwin

Step 3

Add the student class.

In this class we will set the property of the student.

  1. public class Student    
  2. {    
  3.     public int Id { getset; }    
  4.     public string Name { getset; }    
  5.     public string CollegeName { getset; }    
  6.     public string Address { getset; }    
  7. } 
Step 4

Configure Web API for Self-Host.

In this step we will add a class that handles the route as well as make the compatible travel the route according to the URL parameter. For that right-click on the project and select Add / Class to add a new class. Name the class Startup.
  1. using Owin;  
  2. using System.Web.Http;   
  3.   
  4. namespace OWinHost  
  5. {  
  6.   public class Startup  
  7.     {  
  8.         public void Configuration(IAppBuilder appBuilder)  
  9.         {  
  10.             // Configure Web API for self-host.   
  11.             HttpConfiguration config = new HttpConfiguration();  
  12.             config.Routes.MapHttpRoute(  
  13.                 name: "DefaultApi",  
  14.                 routeTemplate: "api/{controller}/{id}",  
  15.                 defaults: new { id = RouteParameter.Optional }  
  16.             );  
  17.   
  18.             appBuilder.UseWebApi(config);  
  19.         }   
  20.     }  
  21. }  
Step 5

Add a Web API Controller.

Now add a Web API controller class. Right-click the project and select Add / Class to add a new class. Name the class StudentController.
  1. namespace OWinHost  
  2. {  
  3.    public class StudentController : ApiController  
  4.     {  
  5.         private static List<Student> student = new List<Student>{  
  6.            new Student{Id=1,Name="rajeev", CollegeName="MIT", Address="New Delhi"},  
  7.            new Student{Id=2,Name="ranjan", CollegeName="MIT", Address="pune"},  
  8.            new Student{Id=3,Name="Jasmine", CollegeName="VIT", Address="Banglor"},  
  9.            new Student{Id=4,Name="Manish", CollegeName="JNU", Address="New Delhi"}  
  10.        };  
  11.         public IEnumerable<Student> GetAll()  
  12.         {  
  13.             return student;  
  14.         }  
  15.         public Student GetById(int id)  
  16.         {  
  17.             var stud = student.FirstOrDefault(x => x.Id == id);  
  18.             if (stud == null)  
  19.             {  
  20.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  21.             }  
  22.             return stud;  
  23.         }  
  24.     }  
  25. }  
Step 6

Start the OWIN host and make a request using HttpClient.
  1. using Microsoft.Owin.Hosting;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net.Http;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace OWinHost  
  10. {  
  11.   public class Program  
  12.     {  
  13.         static void Main()  
  14.         {  
  15.             string baseAddress = "http://localhost:9000/";  
  16.   
  17.             // Start OWIN host   
  18.             using (WebApp.Start<Startup>(url: baseAddress))  
  19.             {  
  20.                 // Create HttpCient and make a request to api/values   
  21.                 HttpClient client = new HttpClient();  
  22.   
  23.                 var response = client.GetAsync(baseAddress + "api/student").Result;  
  24.   
  25.                 Console.WriteLine(response);  
  26.                 Console.WriteLine(response.Content.ReadAsStringAsync().Result);  
  27.             }  
  28.   
  29.             Console.ReadLine();  
  30.         }  
  31.     }  
  32. }  
Output

Output

Summary

In this article we have learned Self Hosting using OWIN.

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


Similar Articles