Overview of OWIN and Katana

Introduction

As OWIN is becoming popular and more common, it is important for ASP.NET developers to understand what OWIN and Katana are. ASP.NET Web API and ASP.NET Identity are already geared towards using these specifications. To that end this article explains what OWIN and Katana are and how they fit into the whole web development picture for ASP.NET developers. You will also develop a simple application to get a code level understanding of these features.

Background

The .NET framework made its appearance sometime in 2002. ASP.NET was bundled as a part of the overall .NET framework. The idea was to provide a unified development framework for building desktop and web applications and services. In those days Windows development tools such as VB6 were common and popular. Naturally, ASP.NET and Visual Studio attempted to provide a RAD (Rapid Application Development) development environment to web developers. Web pages were looked upon as Web Forms backed by a rich server side Page framework. ASP.NET also offered plenty of Server Controls to develop rich user interface elements quickly. Web Forms provided its core functionality through server side events. Developers housed server controls (such as a Button, TextBox and GridView) on a web form and then handled their server side events (such as Click and SelectedIndexChanged). Features such as ViewState and Data Binding were added to make the programing model closer to the desktop application programming model.

Although the Web Forms framework served well for many years, it has its own limitations. The Web Forms framework was a part of the overall .NET framework. This bundling required that the ASP.NET and the .NET framework be released together. It became difficult for Web Forms framework to keep pace with the dynamic and rapidly changing web development trends and needs.

All the Web Forms applications make use of System.Web – the core assembly providing ASP.NET functionality. The System.Web assembly provides a rich set of functionality to web developers. However, the problem is that many times you may use only a small portion of this functionality but you still need to refer to the whole assembly. This is unnecessary and resource consuming. Moreover, System.Web is tightly coupled with IIS. That means your ASP.NET applications can run only on IIS.

The following figure summarizes what we discussed so far.

ASP.NET Application
ASP.NET Application

Over the years the way web applications are built and used has changed. Modern web applications are standards based, lightweight, modular and greatly rely on features such as Ajax for communicating with the server. Considering the above limitations it is difficult for the Web Forms framework to effectively meet the requirements of modern web development. That’s why Microsoft decided to introduce OWIN and Katana into ASP.NET development.

What is OWIN?

OWIN stands for Open Web Interface for .NET. OWIN is a specification that describes how web development frameworks such as ASP.NET MVC should interact with the web servers. The goal of OWIN is to decouple web applications from the web server by introducing an abstraction layer. Such an abstraction enables you to run the same application on all the web servers that support OWIN. Additionally, it simplifies the overall system because the abstraction layer can provide a lightweight infrastructure to host the applications. IIS provides a rich set of features to the web applications. However, web applications may not need all these features. It might be sufficient for them to have minimal HTTP processing capabilities. OWIN compatible host can provide such a hosting environment to these applications. Moreover, you can define a pipeline of modules that are used during the request processing. An OWIN pipeline is a chain of OWIN compatible components through which a request passes.

The OWIN specification is a community initiative and more details can be found at the owin.org website.

What is Katana?

Katana is a set of components by Microsoft built using OWIN specifications. Some of these components include Web API, ASP.NET Identity and SignalR. The following figure shows the overall architecture of a Katana based application.

Overall architecture of a Katana based application
Overall architecture of a Katana based application

As you can see from the figure, there are four layers namely Application, Middleware, Server and Host. Let’s understand the job of each of these layers.

The Application layer indicates your client application. For example, a web site developed in ASP.NET MVC. It could also be a Windows based application or even a console application. This application is used by the end users and it need not do anything special as far as OWIN is concerned.

The middleware layer indicates a set of components built using OWIN specifications. These components can be larger frameworks such as Web API or specialized components such as ASP.NET Identity or SignalR. There can be more than one component in this layer. If so, they can form a pipeline – a chain of components – that is executed before the request reaches the server. You can add or remove the components from this chain through your code.

The third layer is Server. A server listens to an incoming request and performs the relevant network level tasks such as opening a socket. Katana comes with two server components:

  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Host.HttpListener

The SystemWeb host hooks into IIS through an HTTP handler and module. This should be used if you wish to use IIS as your host. The latter is lightweight server developed using .NET framework’s HttpListener class and it is the default in case you decide to create your own host (self-hosting).

The final layer is Host. This layer creates and manages a process for your application. It also provides the overall environment for your application. There are three options for hosting applications based on Katana:

  • IIS
  • OwinHost.exe
  • Custom host

The first option uses IIS as the host. Notice that IIS acts as a host as well as a server. The OwnHost.exe is a readymade lightweight host that you can use to host your applications. If these two options do not meet your requirements you can always create a custom host.

Developing a Simple Application Using OWIN

In this section you will develop a simple application using Katana architecture as discussed earlier. This application consists of the layers discussed above and consists of three main pieces:

  • Windows Forms application that acts as a server and host
  • Web API for retrieving Customer information from the Northwind database
  • Windows Forms application that acts as a client to the Web API

The Web API is bundled in the same project as the Windows Forms host but you can also create it as a separate Class Library type of project if you wish. The following figure shows how the host Windows Forms application looks:

OWIN Self Host Application
OWIN Self Host Application

As you can see the host application consists of a Start button. Clicking on the Start button generates a random port number between 8000 – 9999 and starts an OWIN host at the specified port. The base URL of the host is displayed in a Label control. Closing the form terminates the host.

The client application that calls the Web API is shown below:

Client Application
Client Application

The client application consists of two textboxes and a button. The textboxes are used to specify the port number (as generated and seen in the host application) and a CustomerID respectively. Clicking on the “Call Web API” button invokes the Web API and retrieves the CompanyName of the specified CustomerID. The CompanyName is then displayed in a Label as shown.

The aim of this example is to give you a broad idea of how the OWIN concepts that we have discussed so far look like at code level. Any detailed discussion of the code and classes involved in the example is beyond the scope of this article. So, let’s get going!

Creating the Host Application

Begin by creating a new Windows Forms project in Visual Studio and name the project MySelfHost. Then right click on the References folder and select “Manage NuGet Packages” option. Using the Manage NuGet Packages dialog add a NuGet package for Microsoft ASP.NET Web API 2.1 OWIN Self Host. The following figure shows this package in the dialog.

NuGet package for Microsoft ASP.NET Web API 2.1 OWIN Self Host
NuGet package for Microsoft ASP.NET Web API 2.1 OWIN Self Host

We need this package because it allows you to self host Web API in your own application (Windows Forms application in this case). Adding this package will also add several other dependencies and you can have a look at them using the Installed Packages section of the same dialog (or expand the References folder to have a glance at the new assemblies that get added).

Then add a new class to the project based on the OWIN Startup Class template. The following figure shows this template in Add New Item dialog of Visual Studio:

Add New Item
Add New Item

Name the class as Startup.cs. Once added, import the following namespaces in the Startup.cs file.

using Microsoft.Owin;
using Owin;
using System.Web.Http;

Then add the following code to the Startup class:

[assembly: OwinStartup(typeof(MySelfHost.Startup))]
 
namespace MySelfHost
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultWebApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            app.UseWebApi(config);
        }
    }
}

Notice that the above code uses an assembly level attribute – OwinStartup to specify the Startup class as an OWIN startup class. The Startup class has a method named Configuration() that is responsible for configuring an OWIN application. In this case the HttpConfiguration object defines a default route for Web API requests and then uses UseWebApi() extension method. The UseWebApi() method indicates that we intend to use the Web API framework as an OWIN middleware component. Note that the startup class name need not be Startup as it is configurable through the [OwinStartup] attribute but whatever startup class you create must contain the Configuration() method.

Next, design the Windows Form as shown above (see the figure for Self Host application earlier). Then go in the Windows Forms code editor and import the following namespace:

using Microsoft.Owin.Hosting;

Now add the following code in the Click event of the Start button.

private void button1_Click(object sender, EventArgs e)
{
    Random r = new Random();
    int portNumber = r.Next(8000, 9999);
    string baseUrl = "http://localhost:" + portNumber;
    WebApp.Start<Startup>(baseUrl);
    label1.Text = "OWIN Host Started at " + baseUrl;
}

The above code generates a random port number in the range of 8000-9999 using Random class. It then uses the WebApp.Start() method to start the OWIN host. Notice that the Start() method can also specify the OWIN startup class instead of the [OwinStartup] attribute (any one technique can be used although our code shows both the techniques).

That is all we need to do in order to create an OWIN host.

Creating the Web API

Now we need to create the Customer Web API itself. So, add a Models folder in the same Windows Forms project and add an Entity Framework Data Model for the Customers table to it. The following figure shows the Customer entity in the Visual Studio designer.

Customer Entity
Customer Entity

Next, add a new class to the same project and name it – CustomerController. This is your Web API controller class and is shown below:

namespace MySelfHost
{
    public class CustomerController:ApiController
    {
        public string GetCompanyName(string id)
        {
            NorthwindEntities db = new NorthwindEntities();
            Customer obj = db.Customers.Find(id);
            return obj.CompanyName;
        }
    }
}

The CustomerController class inherits from the ApiController base class (make sure you have imported System.Web.Http and MySelfHost.Models namespaces). It contains GetCompanyName() method that handles GET requests. The GetCompanyName() method accepts a CustomerID as its parameter. Inside, the method simply retrieves a Customer from the Customers DbSet and returns its CompanyName to the caller.

This completes the Web API.

Creating the Client Application

In this final step you will create a Windows Forms client that consumes the Web API hosted in our custom OWIN host. To develop this client application add another Windows Forms project (name it MyClient) to the same solution. Design the form as shown earlier (see the second figure at the beginning of this example). Then write the following code in the Click event handler of the “Call Web API” button.

private void button1_Click(object sender, EventArgs e)
{
    string baseUrl = "http://localhost:" + textBox2.Text;
    HttpClient client = new HttpClient();
    HttpResponseMessage response = client.GetAsync(baseUrl + "/api/customer/" + textBox1.Text).Result;
    label1.Text = response.Content.ReadAsStringAsync().Result;
}

The above code forms the base URL of the host by picking the port number from the textbox. It then creates an instance of HttpClient class (make sure you have referenced System.Net.Http assembly and have imported System.Net.Http namespace). It then makes a GET request to the Web API using the GetAsync() method. Notice that the GetAsync() method forms the complete URL by appending /api/customer/<customer_id>. The response from the Web API is received as HttpResponseMessage. To read the actual CompanyName, ReadAsStringAsync() method is used.

This completes the client application.

Running the Application

Now that you have built all the parts of this example, it’s time to run and test the application. First of all, build the solution. Then run the MySelfHost project. Doing so will launch the host form. Click on the Start button so as to start the host. Note down the randomly generated port number from the base URL of the host. You will need this port number while running the client.

Then run the MyClient project. Enter the port number and a CustomerID in the respective textboxes and click on the “Call Web API” button. If all goes well you should see the CompanyName in the Label.

Summary

Open Web Interface for .NET or OWIN is a specification describing an abstraction that separates your application and the actual web server. Katana is a set of components developed by Microsoft based on the OWIN specifications. Using OWIN you can develop lightweight and modular applications with a possibility of porting them across different web servers. This article presented a quick overview of OWIN and Katana. You also developed a simple yet functional application that hosts Web API in a custom OWIN host.

Extra Reading Links

About the Author:

Bipin Joshi is an author and a .NET trainer who writes about apparently unrelated topics – yoga & technology! Bipin has been programming since 1995 and is working with .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. You can read more about him here.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read