OWIN: Customizing the Web Server

OWIN and Katana are designed to provide a different way of meeting those objectives that currently require the use of NodeJS. With them, you can run extremely thin and super-optimized web server applications by cutting out what you don't need and swapping out those parts that you wish to behave differently. Dino Esposito explains how to get started.

OWIN stands for the Open Web Interface for .NET. If you visit the home page of the OWIN web site at http://owin.org you find out that OWIN aims to define a standard interface for web servers and .NET client applications to interact.  The design of OWIN, you read on the web site-was inspired by Node.js, Rack, and WSGI. Rack (http://rack.github.io) and WSGI (http://wsgi.org) are frameworks similar to Node.js but specific to Ruby and Python environments.

Node.js inspired OWIN because it fulfilled the same user-requirement, but does it in a completely different way.  Node.js allows you to create web servers that operate under your total control. Here, The term “web server” merely refers to a component running on the server that answers your HTTP calls.  NodeJS can imitate the functionality of a classic web server like Apache or IIS but that is not what is appealing to developers so much. More importantly, It means that companies can build their own web server for specific services and shape it as they wish to fit their specific needs, instead of bending IIS, Apache or other “official” web servers. Based on JavaScript, Node.js was fairly easy to customize even though it takes a while to grasp its asynchronous architecture and conventions. OWIN is designed to give the same flexibility, but without the daunting task of replacing the functionality of an established Web Server such as IIS or Apache

Motivation for OWIN

Stated baldly, OWIN is an attempt to replicate in .NET the ecosystem of modules that Node.js is generating outside .NET. In this regard, I don’t think that the whole OWIN thing will ever be attractive to the general run of enterprises that today run their line-of-business applications on top of IIS. Those enterprises will keep on using IIS, deciding whether to upgrade or not to future versions when they hit the market.

So what’s the point of OWIN and why is being talked so much?

As I see it, OWIN is more likely to become a programmable interface exposed by a future version of IIS, rather than to provide a substitute. As it happens, OWIN can dictate the rules by means of which IIS and ASP.NET applications can communicate. OWIN is therefore an interesting way to outline future development to take place around IIS and ASP.NET. It’s not a product; and will not be so until it is fully incorporated in IIS and exposed as a common API that allows you to customize and integrate IIS, or even perhaps to build your own web servers that replace IIS.

I feel confident in saying that the primary use of OWIN will be to customize IIS rather than replace it.

OWIN in a Nutshell

The fundamental idea behind any OWIN interaction is that a task executes asynchronously using data being passed through a dictionary. Any interaction between a web application and an OWIN-based web server is expressed by the following delegate:

The dictionary is expected to contain whatever can be found in the HTTP context including application state, session state, server state, authentication and request information. From the current perspective of an ASP.NET developer, OWIN is just an interface to do exactly the same things that you do today-authentication, cookies, authorization, output caching, headers, request servicing, response except that everything happens through a different interface. Furthermore, this interface is not specifically bound to ASP.NET specific types and modules. In a way, it’s the application of one of the most basic principles of object-oriented design: program to an interface, rather than to an implementation.

A moment ago, I mentioned the HTTP context. To an ASP.NET developer, the HTTP context means a specific class-System.Web.HttpContext-that only in recent versions of ASP.NET has been partly abstracted and replaced by HttpContextBase. The step being taken by the OWIN-inspired redesign is just using an abstract definition of the HTTP context that is as easy and general as a dictionary. The table below describes how common pieces of request and response information map to entries in the OWIN dictionary.

Key

Required

Value

owin.RequestBody

Yes

Contains a stream object filled with the request body.

owin.RequestHeaders

Yes

Contains a dictionary of HTTP request headers. The actual type is set to be IDictionary<String, String[]>.

owin.RequestMethod

Yes

Contains a string that indicates the method of HTTP request: GET, POST or other common HTTP verbs.

owin.RequestPath

Yes

Contains the path of the request path. The path is a string relative to the root of the site.

owin.RequestPathBase

Yes

Contains the portion of the request path corresponding to the root of the site.

owin.RequestProtocol

Yes

Contains the protocol name and version. As an example, it could be HTTP/1.0 or HTTP/1.1.

owin.RequestQueryString

Yes

Contains the query string component of the HTTP request without the leading “?”. It contains the empty string if no query string is found.

owin.RequestScheme

Yes

Contains the URI scheme such as HTTP or HTTPS.

owin.ResponseBody

Yes

Contains a stream object to receive the response.

owin.ResponseHeaders

Yes

Contains a dictionary of HTTP response headers. The actual type is set to be IDictionary<String, String[]>.

owin.ResponseStatusCode

No

Contains the integer denoting the HTTP response status code.

owin.ResponseReasonPhrase

No

Contains the reason phrase associated the given status code

owin.ResponseProtocol

No

Contains the protocol name and version. As an example, it could be HTTP/1.0 or HTTP/1.1.

owin.CallCancelled

No

Contains information that indicates whether the request was cancelled or aborted.

owin.Version

No

Contains a string that indicates the OWIN spec version.

The table only contains the basic set of entries to have web servers and application to communicate; custom entries if required can be added.

Katana in a Nutshell

Microsoft has some work done to implement the OWIN specification. The set of components that allow you to implement a conversation between applications and web server on .NET via the OWIN interface goes under the name of Katana. Katana is lets you build a web solution without having to rely on Web Forms or ASP.NET MVC and without even hosting the final artifact on IIS. If this idea doesn’t attract you or just scares you, then you should ignore OWIN and Katana. 

The vision behind Katana is that a web solution is built around a couple of key blocks: markup generation and AJAX requests. In addition, there will probably be static file-serving to consider. This is what one typically expects from a web application running through a HTTP endpoint. Let’s see what it could take to write an OWIN-compatible application.

Markup Generation

You can start by creating an empty ASP.NET project in Visual Studio 2013. As Figure 1 demonstrates, the empty project doesn’t have any dependencies on System.Web.

1933-clip_image001-620x407.jpg

Figure 1. System.Web is an unused reference in default empty ASP.NET project in Visual Studio 2013.

In the near future ASP.NET MVC will, I expect,  be delivered in a way that doesn’t bind it to the ASP.NET infrastructure (i.e., System.Web). However, for the time being you need an alternative framework for serving server-side generated pages. The canonical Microsoft example uses the NancyFx framework (see http://msdn.microsoft.com/en-us/magazine/dn451439.aspx). The code snippets that I present here are based, instead, on the code discussed here: http://blog.micic.ch/net/owin-and-razor-enabled-mvc-application-framework.

Any OWIN-based application begins with a startup class where the routing engine is initialized. There are various ways to specify the entry point in an OWIN solution. The most common approach consists in just having a public class named Startup with a method called Configuration, as below:

The Route class is defined within the custom framework and has nothing to do with the Route class of ASP.NET. The class Middleware is the core of the minimal OWIN framework based on the aforementioned blog post. The effect of the code above is that the OWIN middleware is aware of a route that must be mapped to the DemoController class. The view engine also is a custom framework that uses the RazorEngine Nuget package to render CSHTML files to HTML pages.

AJAX Requests

You can complete the web solution with a Web API infrastructure that is respectful of the OWIN standard. The “Microsoft ASP.NET Web API 2 OWIN” Nuget package is what you need. Once you install the package you also need to extend the startup class with the following lines:

The code hidden by the UseWebApi extension method has the same structure of the Middleware class discussed above. It knows how to process a request using the public interface as defined in the OWIN standard. The Middleware class is the entry point of the request and is based on the OWIN core delegate which gets a dictionary of values and returns an async task.

The factory uses the entries in the table above to access information about the request. Based on that information, the factory figures out the way to generate the response. In particular, in the example the same Razor engine of ASP.NET MVC is used to process CSHTML source files.

HTTP Listeners and Host Application

The missing link to put the whole OWIN thing together is the host application doing HTTP listening. This is the work that is usually accomplished by IIS core components. You can refer to yet another Nuget package Microsoft.Owin.HttpListener that performs HTTP listening and is currently the default option for self-hosting. At this point, you only miss the executable that runs the application. The OwinHost Nuget package brings the owinhost.exe program that works according to the diagram below.

1933-clip_image003.jpg

Figure 2. The data flow of an OWIN-based host solution

By default, the owinhost.exe application, as available in the Katana project, loads the HTTP listener right upon launch and then begin listening on port 5000. The port is configurable on the command line. To invoke the application and send requests all you do is calling http://localhost:5000 or use the IP address of choice.

Summary

At this point of reading  this article, I hope you have formed an idea of how the whole thing works. You don’t need a deep understanding of the whole code to understand the mechanics; and understanding the mechanics raises again the key question. What are some concrete benefits of OWIN? Sure, you can set up a web solution without using IIS and without using ASP.NET and its core assemblies. Moreover, you can build the solution around a common interface that has been outlined to become a standard.  Is this there enough reason to adopt OWIN if  you’re happy with IIS?

OWIN’s benefit is that it allows you to keep your options open.  If you don’t need it, OWIN will remain transparent once it is  integrated into IIS and all parts of the ASP.NET framework. However, if you want more, OWIN gives you a way to run .NET web applications outside of IIS natively and without the need of a virtual machine. In addition, OWIN allows to arrange extremely thin and super-optimized web server solutions where you can easily cut off what you don’t need and completely unplug and replace those parts that you wish to behave differently. And, more than everything else, you can do this in a relatively easy and safe way.

For a deeper understanding and for some reproducible code I do recommend you read the two articles mentioned in this article: