ASP.NET Web API OWIN Self Host on Windows Azure

In this blog post, I will take a look at Open Web Interface for .NET (OWIN) and will also demonstrate how to deploy ASP.NET Web API app on Windows Azure Worker Role using OWIN and OWIN HttpListener server provided by OWIN self host infrastructure. The OWIN HttpListener server lets you host ASP.NET Web API within your own process. In this demo, I will host the ASP.NET Web API app within a Windows Azure Worker Role.

Introduction to OWIN

Open Web Interface for .NET (OWIN) is a community-owned specification, which defines an abstraction between .NET web servers and .NET web applications. The goal of the OWIN interface is to decouple the web servers from the web applications so that the .Net developer communicate can easily create modules and hosting infrastructures for the web development and deployment. This is a right path to the .Net developer community, which enable a proper open source ecosystem, that was lacking in the .Net web development. OWIN lets the .Net developer communities to develop frameworks and servers for web development and deployment, based on the OWIN specification. For an example, you don’t need an IIS web server for deploying your .Net web app. You can use a minimalist server infrastructure for hosting your web app which can also provide better performance than hosting on IIS since it is a minimalist hosting infrastructure. OWIN provides the flexibility like Node.js does. Node.js is a platform with very limited internal modules, where community have been developing minimalist modules and distributing it through NPM. The same kind of flexibility we can achieve through OWIN where we can distribute re-usable modules through NuGet like NPM does for Node.js. The power of Node.js platform is its community. It would be great if we could develop lot of minimalist frameworks for solving different kind of problems, instead of developing a single full fledged framework for solving all kind of problems.

IMHO, all software development frameworks should be developed by developer communities with a proper open source ecosystem. Now days, it would be very difficult to independently develop and manage a framework by a platform vendor. Instead of it, the developer community should develop the frameworks and pluggable modules, so that development tools can cope with latest trends, standards and can compete with other frameworks of other open source community. So OWIN specification is a great step from Microsoft and community. Now the .Net developer community should develop great modules, frameworks and servers for the .Net web development stack. I believe that platform vendors like Microsoft can lead the open source movement where developer communities can contribute to the platform. The .Net developer community should learn the open source enthusiasm from other developer communities such as Node.js and Ruby communities.

The information below provides the frameworks and servers which is OWIN compatible:

Servers and Hosts

  • Katana
  • Nowin

Frameworks

  • Nancy
  • SignalR
  • WebApi
  • FubuMVC
  • Simple.Web

Deploying ASP.NET Web API OWIN Self Host on Windows Azure

In this sample demo, I will host the ASP.NET Web API in a Windows Azure Worker Role by using HttpListener server, provided by OWIN. Let’s create Windows Azure Cloud Service project in Visual Studio and add a Worker Role onto the Windows Azure Solution for self hosting ASP.NET Web API.

image

Let’s add the NuGet package Microsoft.AspNet.WebApi.OwinSelfHost into the Worker Roles project where we will put ASP.NET Web API and provide the host for Web API app. Since this package is a a pre-release version, you have to specify the command “–Pre” in the NuGet package manager console window as shown in the below:

PM> Install-Package Microsoft.AspNet.WebApi.OwinSelfHost –Pre

If you are adding the package using Manage NuGet Packages window, you must choose Include Prerelease as shown in the below figure.

image

Let’s add a HTTP Endpoint in our Windows Azure Worker Role for OWIN self host so that OWIN host can listen at the specified HTTP Endpoint . In the Windows Azure project, expand Roles folder, right click on the Worker Role and select properties. In the properties window, select Endpoints and click Add Endpoint.

image

Here we have added an HTTP Endpoint named ApiEndpoint and specified port 80 for private and public ports.

Adding ASP.NET Web API Controller

In the previous steps, we have added OWIN self host NuGet package and added an HTTP endpoint for using the ASP.NET Web API self host. Let’s add a ASP.NET Web API Controller which we will configure in OWIN self host on later steps. Let’s add controller named CategoryController

   1:  public class CategoryController : ApiController 
   2:  {
   3:      Category[] categories = new Category[] 
   4:      { 
   5:          new Category { Id = 1, Name = "Books",
   6:              Description = "IT Books" }, 
   7:          new Category { Id = 2, Name = "Electronics",
   8:              Description = "Electronics Gadgets" }, 
   9:              
  10:      };
  11:      public IEnumerable<Category> Get()
  12:      {            
  13:          return categories;
  14:      }
  15:   
  16:      public HttpResponseMessage Get(int id)
  17:      {
  18:          var category = categories.FirstOrDefault((c) => c.Id == id);
  19:          if (category == null)
  20:          {
  21:              throw new HttpResponseException(HttpStatusCode.NotFound);
  22:          }
  23:          return Request.CreateResponse(HttpStatusCode.OK, category);
  24:      }
  25:  }

The Category class is given below

   1:  public class Category
   2:      {
   3:          public int Id { get; set; }
   4:          public string Name { get; set; }
   5:          public string Description { get; set; }      
   6:      }

Configure Self-Host and Start OWIN Host for ASP.NET Web API

We have added our ASP.NET Web API Controller which we are going to host on OWIN host. For doing this, we have to do the following things:

  1. Configure the ASP.NET Web API for OWIN Self-Host
  2. Start the OWIN Host for listening at a HTTP Endpoint for requests on ASP.NET Web API

Let’s add a Startup class for configure the ASP.NET Web API on OWIN Self-Host.

   1:  using Owin;
   2:  using System.Web.Http;
   3:  namespace WebAPIDemo
   4:  {
   5:  class Startup
   6:  {
   7:    public void Configuration(IAppBuilder app)
   8:    {
   9:      HttpConfiguration config = new HttpConfiguration();
  10:          config.Routes.MapHttpRoute(
  11:              "Default",
  12:              "{controller}/{id}",
  13:              new { id = RouteParameter.Optional });
  14:   
  15:          app.UseWebApi(config);
  16:      }
  17:  }
  18:  }

The IAppBuilder interface provided by OWIN assembly, is used to configure the ASP.NET Web API for self host. Now we have to run the OWIN host within the Worker Role instance. Open the WorkerRole.cs file for running the OWIN Host. The compete implementation of the WorkerRole.cs is provided below:

   1:  using System;
   2:  using System.Diagnostics;
   3:  using System.Net;
   4:  using System.Threading;
   5:  using Microsoft.WindowsAzure.ServiceRuntime;
   6:  using Microsoft.Owin.Hosting;
   7:  namespace WebAPIDemo
   8:  {
   9:  public class WorkerRole : RoleEntryPoint
  10:  {
  11:    private IDisposable app = null;
  12:    public override void Run()
  13:    {
  14:     Trace.TraceInformation("WebAPIDemo entry point called",
  15:         "Information");
  16:      while (true)
  17:      {
  18:          Thread.Sleep(10000);
  19:          Trace.TraceInformation("Working", "Information");
  20:      }
  21:     }
  22:   
  23:    public override bool OnStart()
  24:    {
  25:      // Set the maximum number of concurrent connections 
  26:      ServicePointManager.DefaultConnectionLimit = 12;
  27:             
  28:      // Run OWIN Host
  29:      var endpoint = RoleEnvironment.CurrentRoleInstance.
  30:          InstanceEndpoints["ApiEndpoint"];
  31:      string baseUri = string.Format("{0}://{1}",
  32:          endpoint.Protocol, endpoint.IPEndpoint);
  33:   
  34:      Trace.TraceInformation(String.Format("Starting OWIN at {0}",
  35:          baseUri),"Information");
  36:   
  37:      app = WebApp.Start<Startup>(new StartOptions(url: baseUri));
  38:   
  39:      return base.OnStart();
  40:             
  41:    }
  42:   public override void OnStop()
  43:    {
  44:      if (app != null)
  45:      {
  46:          app.Dispose();
  47:      }
  48:      base.OnStop();
  49:    }
  50:   }
  51:  }

In the OnStart method of WorkerRole.cs, we are running the host by calling the WebApp.Start method where we are specifying the start-up class which we have configured ASP.NET Web API on OWIN Self-Host, and an Uri for listening HTTP requests. We are creating the Uri from the HTTP endpoint we have created for our Worker Role.

   1:  // Run OWIN Host
   2:      var endpoint = RoleEnvironment.CurrentRoleInstance.
   3:          InstanceEndpoints["ApiEndpoint"];
   4:      string baseUri = string.Format("{0}://{1}",
   5:          endpoint.Protocol, endpoint.IPEndpoint);
   6:   
   7:      Trace.TraceInformation(String.Format("Starting OWIN at {0}",
   8:          baseUri),"Information");
   9:     //Start OWIN Host
  10:      app = WebApp.Start<Startup>(new StartOptions(url: baseUri));

Running the Web API App with Windows Azure Compute Emulator

We have completed our ASP.NET Web API and configured it on OWIN host. Let’s test the app locally using Azure Compute Emulator. Let’s run the app locally and right click on the Windows Azure Compute emulator icon and select Show Compute Emulator UI. This will show the Windows Azure Compute Emulator

image

image

We can find the local IP address assigned by the Windows Azure Compute Emulator. Let’s navigate to the Uri http://127.0.0.1:81/category as http://127.0.0.1:81 is assigned as local IP address.

image

Deploying the App to Windows Azure

Let’s deploy the Windows Azure Cloud Service app on Windows Azure and test the app for the Web API endpoints /category and /category/{id}.

image

image

The above screenshots shows that ASP.NET Web API has been successfully running in the OWIN self host within the Windows Azure Worker Role instance.

Summary

In this blog post, we have discussed about Open Web Interface for .NET (OWIN). OWIN is a community-owned specification, which defines an abstraction between .NET web servers and .NET web applications. The primary goal of the OWIN interface is to decouple the web servers from the web applications. Based on OWIN specification, .Net developer community can create open source web development frameworks and hosting infrastructures. In this post, we have deployed our ASP.NET Web API app in self host provided by OWIN. In this demo, we have deployed our ASP.NET app without using a IIS Web Server.

You can follow me on Twitter @shijucv

 

1 Comment

  • I do accept as true with all the concepts you've presented on your post.
    They are really convincing and can definitely work.
    Nonetheless, the posts are too short for novices.
    May just you please lengthen them a bit from next time?
    Thank you for the post.

Comments have been disabled for this content.