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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

15 Responses to OWIN and Katana part 1: the basics

  1. Pingback: Dev.Cast 71 – OWIN och Katana

  2. Jimbo says:

    Great tutorial! Thanks!

  3. cristinapienescu says:

    where is the HTML for the welcome page? Is it hard-coded in one of the Katana dlls? thanks for the tutorial

    • Andras Nemes says:

      Hello,
      This specific default welcome page is hard-coded within the parameterless UseWelcomePage extension. Take a look at the different overloads of this method here to show a custom page.
      //Andras

  4. rnduser says:

    Is there any way to not hardcode but listen to port 7990 in the default hostname? I’m having issues hosing this because it says localhost …
    string uri = “http://localhost:7990”;

    • Andras Nemes says:

      I’m not sure what you mean. What is the issue with localhost? Can you explain what you mean by “not hardcode but listen to port 7990 in the default hostname”?
      //Andras

      • rnduser says:

        What if my default hostname of the machine I’m running is not localhost? The issue I’m having is I can browse http://localhost:7990 in my machine which is hosting it but not from the networked machined which is otherwise able to access other stuff hosted via IIS?

  5. Christian says:

    Thanks for the tutorial!

    How can i get acces to the hostet page from other devices in same network?
    Which host adress is necesarry?

  6. Pingback: CODEFUSION by Marcin Kawalerowicz

  7. Blue clouds says:

    simple steps .. nicely done!

  8. Pingback: Owin & Katana | tuandom's Blog

  9. Raghu jain says:

    Hi Andras Nemes,

    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.

    As in your article mention about it, how can i construct that kind of application?

  10. Guest reader says:

    Great tutorials.Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: