OWIN and Katana part 2: the Application Function

Introduction

In the previous post of this series we started looking into OWIN and Katana. We also looked at a small, very basic Console based web server to see them in action.

We’ll continue digging into how these technologies work. We’ll build upon the demo application we started working on in the previous post so have it ready in Visual Studio.

The Application Function

The application function, or AppFunc is a tool that defines how elements process incoming HTTP requests to the server. It provides a delegate which returns a Task and accepts an IDictionary of string and object. We saw an example of such a Func in the first post of this series. The dictionary represents the request environment. Recall the Environment property of the IAppBuilder interface which is also of the same dictionary type. We also said that this structure is characteristic of OWIN as it lacks any higher level abstraction. It is not a dictionary of, say, RequestParameter and RequestKey with built-in properties which we could expect in a built-in object oriented .NET class. This particular dictionary includes all types of data about the request from and the response to the client: headers, cookies, server variables etc.

The application function delegate always returns a Task to adhere to the asynchronous programming model of modern .NET applications. At this point you should be familiar with the await-async keywords in C#. If not, then start here.

You’ll probably notice that this is quite low-level programming compared to writing a “normal” ASP.NET web application where you get all HTTP related tasks for free from the System.Web library and IIS as the default server. In OWIN you are free to build all components required to fulfil a request. The components will be independent from each other but still able to work together in a decoupled fashion. One component may check the request headers, another one the authentication cookies etc. Every component will have an application function that can be invoked externally. The components form a chain of actions where each component calls upon the next component’s application function in the pipeline using the data in the Environment dictionary mentioned above. As the dictionary object only contains strings and objects the chain remains very loosely coupled.

Demo

Open the console web server we started working on previously in Visual Studio. If you recall then we tested two methods of IAppBuilder: UseWelcomePage and Run. We’ll try something different this time. Add a new class to the solution called WelcomeComponent. Our goal is to write some greeting to every request at a lower level than we did previously. The class will need to come in contact with the IAppBuilder somehow. We’ll need to add a method that matches the Func delegate signature of AppFunc. Insert the following method stub into WelcomeComponent:

public Task Invoke(IDictionary<string, object> environment)
{
    throw new NotImplementedException();
}

Locate Startup.Configuration, comment out the call to appBuilder.UseWelcomePage and insert the following call instead:

appBuilder.Use<WelcomeComponent>();

The Use method will insert a component into the OWIN pipeline. Run the application and you should get an exception: MissingMethodException. The compiler is testing the OWIN components that you wired up using Reflection. If it finds any missing element it will tell you about it. In this case the error message says that “WelcomeComponent does not have a constructor taking 1 argument”. That argument is the AppFunc for the next component in the invocation chain. By now we know what an AppFunc delegate looks like so insert the following constructor stub:

public WelcomeComponent(Func<IDictionary<string, object>, Task> appFunc)
{
}

As an aside: there’s a little trick to make this constructor more concise. Add the following using statement underneath the others:

using ApplicationFunction = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

…the constructor becomes…:

public WelcomeComponent(ApplicationFunction appFunc)
{
}

The incoming appFunc variable represents the next component in the component chain. Add the following private field to the class:

private readonly ApplicationFunction _nextComponent;

…and so the constructor will look like the following:

public WelcomeComponent(ApplicationFunction appFunc)
{
	if (appFunc == null) throw new ArgumentNullException("AppFunc of next component");
	_nextComponent = appFunc;
}

We’ll also implement the Invoke method in a simplistic way:

public async Task Invoke(IDictionary<string, object> environment)
{
	await _nextComponent(environment);
}

So we await the next component and pass along the incoming environment variable to its constructor, just like the way how WelcomeComponent would be called in the pipeline.

A short aside: the Invoke method must be called Invoke, so I didn’t just pick this name. Change the method to something else, like MickeyMouse and then run the application. You should get a System.ArgumentException complaining about a conversion error.

Rename the method to ‘Invoke’. Add a breakpoint within the Invoke method and run the application. You should see a console window with the message that the web server has started. Navigate to localhost:7990 in a web browser and code execution should stop at the break point. Hover over the incoming ‘environment’ variable with the mouse to inspect its contents. In particular take a look at what’s available in the dictionary:

AppFunc dictionary contents

So there are 29 keys and 29 values – this number may change in future updates to the OWIN-related assemblies. Looking through the key names it will be clear immediately that it’s possible to extract just about any information related to the HTTP request: path, headers, request method, request body etc. This environment variable will make sure that the HTTP request properties will be available to every component in the chain. Some of them are actually specified as compulsory elements by the OWIN specification.

You can in fact stop the invocation chain right here and return a response to the caller already now. In that case you’ll need to access the “owin.ResponseBody” dictionary element. Stop the application and comment out the await statement in the Invoke method. The response body will be a Stream so we’ll extract it from the environment dictionary as follows:

Stream responseBody = environment["owin.ResponseBody"] as Stream;

We then construct a StreamWriter out of this and write to the response stream:

using (StreamWriter responseWriter = new StreamWriter(responseBody))
{
	return responseWriter.WriteAsync("Hello from the welcome component");
}

Remove the ‘async’ from the method declaration as the WriteAsync method already returns a Task. Run the application and navigate to localhost:7990 in a browser. You should see the plain message we provided above to the WriteAsync method. This was in fact a very low level Katana component, probably the lowest level possible.

The methods we tested with IAppBuilder, i.e. Run and UseWelcomePage, use the same technique behind the scenes. They are simply wrappers around a much more elaborate Invoke method.

We can make it so that our glorious implementation of the Invoke method becomes available to other programmers using an extension method. Add a new class to the project called AppBuilderExtensions:

public static class AppBuilderExtensions
{
	public static void UseWelcomeComponent(this IAppBuilder appBuilder)
	{
		appBuilder.Use<WelcomeComponent>();
	}
}

We can call this extension method in Startup.Configuration as follows:

appBuilder.UseWelcomeComponent();

This produces the same behaviour as before, just with a little nicer syntax. You’ll notice that the UseWelcomeComponent method call looks very much like UseWelcomePage – the implementation of the latter is probably slightly more involved however.

Components in OWIN are also called middleware as they sit in the middle of the processing pipeline. We’ll keep looking at OWIN middleware in the next post.

View the list of MVC and Web API related posts here.

OWIN and Katana part 1: the basics

Introduction

Katana is a new light-weight web framework built by Microsoft. It is based on a specification called OWIN – Open Web Interface for .NET. The default MVC5 template in Visual Studio 2013 have elements of Katana and OWIN.

Think of Katana as a web framework such as ASP.NET which interacts with IIS as the hosting environment. IIS provides a rich set of features for logging, tracing, monitoring etc. These features are not always needed. With the advent of HTML5 and some very advanced JavaScript libraries like jQuery, Knockout.js, Angular.js etc. a lot of work has been delegated to the client. It is often no longer the server that produces HTML – it only responds to Ajax calls with JSON and it is up to the client to process it. This applies especially to mobile applications that consume cloud based web services which only respond with JSON. The goal is to simplify web hosts to make them more responsive, more scalable and cheaper to maintain as the processing time of a request will be a lot faster. Node.js is a JavaScript-based framework that you can use to build a very lean and efficient web server which only has a limited number of features compared to IIS but suits the needs of a large number of web service consuming applications.

Katana allows you to build web based applications, such as MVC or Web API (2) where you can decide which web features to include in the project. Katana features are highly modularised. Instead of including the entire System.Web library even in the smallest web applications, you can decide which features to include and exclude. As mentioned above, Katana builds on OWIN to achieve these goals. OWIN is a specification which defines an an easy and decoupled form of communication between frameworks and servers. With Katana you can build applications that only indirectly use the features in System.Web through OWIN interfaces. Such an application can be hosted on any server that supports OWIN so it is not tightly coupled to IIS.

Normally a .NET MVC web application references the entire System.Web namespace which has a very large amount of features of which your application may only need a fraction. Also, it will be tied to IIS. Katana takes an other approach with its portable, modular and lightweight components.

I won’t test your patience any longer – let’s see a demo! We’ll build both a Console and a Web application so I have downloaded Visual Studio Express for Web and Desktop. If you have the full version of VS 2013 then you’ll be fine.

Demo

Open Visual Studio 2013 for Windows and create a new Console application. Call it KatanaBasics. Install the following NuGet packages:

Owin hosting nuget package

HttpListener owin package

The Hosting package will also install a number of dependencies such as Owin and Microsoft.Owin. These are the core Katana libraries. Owin contains the core OWIN abstractions, whereas Microsoft.Owin is the Microsoft extension to OWIN. The HttpListener library includes classes to communicate with the operating system. It also enables us to build a small app that listens to HTTP requests on a port. Which is what we’re planning to build here.

Add a new class to the project called Startup which will configure Katana. Be exact and call it “Startup”. When working with Katana you’ll see these Startup classes all the time. The Startup class must have a Configuration method which accepts an IAppBuilder object which resides in the Owin namespace. Add the following stub to the Startup class:

public void Configuration(IAppBuilder appBuilder)
{

}

IAppBuilder includes methods that help us configure an application, in particular how it will respond to HTTP requests. There are a lot of extension methods to the IAppBuilder interface. They are available in different Owin-related libraries. So as you reference additional Owin packages from NuGet you’ll see new extension methods available for the IAppBuilder interface. This provides you a way to enable new features as they become necessary.

The Run() extension method helps us configure how the application will handle HTTP requests. Katana will call into this method to process the requests. It accepts a Func delegate which returns a Task object and accepts an IOwinContext object as parameter.

Start typing the following within the Configuration method:

appBuilder.Run(owinContext =>
	{
		owinContext.
	});

This is a lambda expression that accepts an IOwinContext object which will be inferred by the compiler. As you type “owinContext.” IntelliSense will provide a list of interesting properties:

  • Authentication: to access properties of the current user, such as Claims
  • Environment: helps you to retrieve a range of OWIN-related properties from the current OWIN context
  • Request: to access the properties related to the HTTP request such as headers and cookies
  • Response: to build and manipulate the HTTP response

The Environment property returns a type of IDictionary of string and object which is quite generic and is characteristic of OWIN. Normally in ASP.NET we have access to strongly typed classes when we extract information about the incoming HTTP request. Here, however, the information is stored in a generic dictionary of the very basic “string” and “object” objects. OWIN aims to provide a simple API without a lot of specialisation.

In this very first demo we’ll only return a simple string to all callers using the Response property:

appBuilder.Run(owinContext =>
	{
		return owinContext.Response.WriteAsync("Hello from OWIN web server.");
	});

WriteAsync returns a Task so it is perfectly suitable for our Func delegate.

We’ll define the URI and port number in the Main method where the console app will be listening. We’ll also use another object from OWIN called WebApp to set up our web server. It is a Katana component residing in the Microsoft.Owin.Hosting namespace. It has a Start method where you can specify the class that includes your configuration. Add the following code to Main:

string uri = "http://localhost:7990";

using (WebApp.Start<Startup>(uri))
{
        Console.WriteLine("Web server on {0} starting.", uri);
        Console.ReadKey();
	Console.WriteLine("Web server on {0} stopping.", uri);
}

If you have anything running on port 7990 then select something else. All we do within the using block is let the world know that we’re starting the server. We can stop the server by pressing a button which is what the ReadKey is waiting for. That’s it really, we have just written a web server. Press F5 to start the application. You should see a console window popping up with the start-up message. Then open a browser and navigate to http://localhost:7990. You should see the welcome message in the browser:

Console web server running in browser

Let’s make the welcome page a bit more interesting. Download the following NuGet package:

Owin diagnostics NuGet package

The Diagnostics package includes the components to build a default home page. The IAppBuilder interface has now a new extension method available called UseWelcomePage. Update the Configuration method as follows:

public void Configuration(IAppBuilder appBuilder)
{
	appBuilder.UseWelcomePage();			
}

Start the console app again and navigate to localhost:7990. You should see a nice blue page such as this one:

Owin default homepage

We’ll dig deeper into OWIN and Katana in the next post.

View the list of MVC and Web API related posts here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: