Click here to monitor SSC
  • Av rating:
  • Total votes: 9
  • Total comments: 0
Dino Esposito

OWIN: Customizing the Web Server

03 February 2014

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:

Func<IDictionary<String, Object>, Task>;

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.

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:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
       app.Use(new Func<object, object>(
          x => new Middleware(new List<Route>
          {
             new Route("Demo", typeof (DemoController))
          })
       ));
    }
}

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:

var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DemoApi", "api/{Controller}");
app.UseWebApi(config);

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.

public async Task<object> Invoke(IDictionary<string, object> environment)
{
    var handler = RequestFactory.Get(environment, this.Routes);
    await handler.Handle();
    return Task.FromResult<object>(null);
}

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.

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:

·         http://msdn.microsoft.com/en-us/magazine/dn451439.aspx)

·         http://blog.micic.ch/net/owin-and-razor-enabled-mvc-application-framework

Dino Esposito

Author profile:

A long-time trainer and consultant, Dino is the author of many popular books for Microsoft Press for .NET developers.including “Architecting Mobile Solutions for the Enterprise“ and “Programming ASP.NET MVC” both for Microsoft Press. CTO of Crionet, a firm specializing in Web-based and mobile solutions for sport events across Europe (http://www.crionet.com), at the moment Dino is also technical evangelist for JetBrains, where he focuses on Android and Kotlin development, and member of the team that manages WURFL—the database of mobile devices used by organizations such as Google and Facebook. Follow Dino through his blog at http://software2cents.wordpress.com or at http://twitter.com/despos

Search for other articles by Dino Esposito

Rate this article:   Avg rating: from a total of 9 votes.


Poor

OK

Good

Great

Must read
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.
 

Top Rated

Acceptance Testing with FitNesse: Multiplicities and Comparisons
 FitNesse is one of the most popular tools for unit testing since it is designed with a Wiki-style... Read more...

Acceptance Testing with FitNesse: Symbols, Variables and Code-behind Styles
 Although FitNesse can be used as a generic automated testing tool for both applications and databases,... Read more...

Building Performance Metrics into ASP.NET MVC Applications
 When you're instrumenting an ASP.NET MVC or Web API application to monitor its performance while it is... Read more...

Acceptance Testing with FitNesse: Documentation and Infrastructure
 FitNesse is a popular general-purpose wiki-based framework for writing acceptance tests for software... Read more...

TortoiseSVN and Subversion Cookbook Part 11: Subversion and Oracle
 It is only recently that the tools have existed to make source-control easy for database developers.... Read more...

Most Viewed

A Complete URL Rewriting Solution for ASP.NET 2.0
 Ever wondered whether it's possible to create neater URLS, free of bulky Query String parameters?... Read more...

Visual Studio Setup - projects and custom actions
 This article describes the kinds of custom actions that can be used in your Visual Studio setup project. Read more...

.NET Application Architecture: the Data Access Layer
 Find out how to design a robust data access layer for your .NET applications. Read more...

Calling Cross Domain Web Services in AJAX
 The latest craze for mashups involves making cross-domain calls to Web Services from APIs made publicly... Read more...

Web Parts in ASP.NET 2.0
 Most Web Parts implementations allow users to create a single portal page where they can personalize... Read more...

Why Join

Over 400,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.