Web API Hosting From OWIN With Windows Azure

Introduction

In this article, we will learn about the hosting of the Web API. We will do it from the Azure Worker Role using OWIN. As you know, OWIN is used for decoupled architectures between a Web Server and a Web Application.

In that context, OWIN is the ideal web interface for self-hosting the Web API. We'll use the HttpListener of OWIN to self-host the application based on OWIN.

Prerequisites

The following are the prerequisites.

  • Visual Studio 2012 or later
  • Windows Azure SDK for Visual Studio 2012

So, let's start the application development with the following sections.

  • Windows Azure Project
  • OWIN Package Installation
  • Role Endpoint
  • API Configuration
  • API Controller
  • OWIN Hosting
  • Azure Emulator

Windows Azure project

In this section, we'll create an Azure Project. Proceed with the following.

Step 1. Open the Visual Studio with an Administrator Privilege.

Discover what's new in ultimate

Step 2. Choose the Azure Cloud Service and enter the service name.

Window azure cloud service

Step 3. In the next wizard, double-click the Worker Role and enter the worker role name.

Work role

Visual Studio automatically creates the Windows Azure Cloud Service with the Worker Role.

OWIN package installation

In this section, we will add the OWIN package and the Web API. To add it you need to open the Package Manager Console and write the following command.

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost -Pre.

Install package

Role endpoint

In this section, we'll add the endpoint and protocol modification.

Step 1. Select your worker role and open the properties.

API worker role

Step 2. Click on "Add Endpoint".

Endpoints

Step 3. Enter the Endpoint name (you can also leave it as-is). Edit the public and private ports.

OwinEndpoint

API configuration

Add a new class named Startup by right-clicking on the worker role.

Class

Replace the code with the following code.

using Owin;
using System.Web.Http;
namespace ApiWorkerRole
{
    class Startup
    {
        public void Configuration(IAppBuilder MyOwinApp)
        {
            HttpConfiguration OwinConfig = new HttpConfiguration();
            OwinConfig.Routes.MapHttpRoute("Default", "{Controller}/{defaultid}", new { defaultid = RouteParameter.Optional });
            MyOwinApp.UseWebApi(OwinConfig);
        }
    }
}

API controller

Now, add a class on the worker role and enter the name. Replace the code with the following code.

using System;
using System.Net.Http;
using System.Web.Http;
namespace ApiWorkerRole
{
    class CheckController : ApiController
    {
        public HttpResponseMessage GetText()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("Hello This is Owin from Azure")
            };
        }
        public HttpResponseMessage GetText(int appid)
        {
            string Message = String.Format("Hello This is Owin on (appid= {0})", appid);
            return new HttpResponseMessage()
            {
                Content = new StringContent(Message)
            };
        }
    }
}

OWIN hosting

Open WorkerRole.cs from the Solution Explorer and add the following code to the Run () method.

private IDisposable MyApp = null;

Now, modify your code with the following code.

using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.Owin.Hosting;
namespace ApiWorkerRole
{
    public class WorkerRole : RoleEntryPoint
    {
        private IDisposable MyApp = null;
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.TraceInformation("ApiWorkerRole entry point called", "Information");
            while (true)
            {
                Thread.Sleep(10000);
                Trace.TraceInformation("Working", "Information");
            }
        }
        public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 50;
            var AppPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["OwinEndpoint"];
            string identifier = string.Format("{0}://{1}",
                AppPoint.Protocol, AppPoint.IPEndpoint);
            Trace.TraceInformation(String.Format("OWIN URL is {0}", identifier),
                "Information");
            MyApp = WebApp.Start<Startup>(new StartOptions(url: identifier));
            return base.OnStart();
        }
        public override void OnStop()
        {
            if (MyApp != null)
            {
                MyApp.Dispose();
            }
            base.OnStop();
        }
    }
}

Azure emulator

Press F5 to start the execution. This will open the Windows Azure Emulator. You must run Visual Studio with Administrator Privileges to show the Emulator.

To open the Emulator.

Show compute emulator ui

The Azure Emulator designates an IP address to your endpoint. You can also open the web browser with your address and controller name.

Deployment

Summary

This article introduced you to the Azure Cloud Service and the Azure Worker Role. You can add the OWIN self-hosting package to your API and End Points. Thanks for reading.


Recommended Free Ebook
Similar Articles