OWIN stands for Open Web Interface for .NET. Now if you are thinking, .NET already has ASP.NET and MVC and Web API, how does this OWIN thing fit in? Is it a new tool/library/web framework, and then what is Katana?
Well OWIN is an open, industry standard or a specification and is primarily authored by two members of the ASP.NET Team - Benjamin Vanderveen and Louis Dejardin. You can compare OWIN with RACK in Ruby and WSGI from the Python world. For now let’s call it as a specification of interoperability between webhosts and frameworks, that outlines ‘some’ rules for building ‘certain’ types of .NET applications.
The Katana project by Microsoft picks up these rules and has created an implementation of the specification. So OWIN is like the blueprint whereas the Katana project uses the blueprint to create increasingly useful set of modules that adhere to the OWIN rules. Don’t worry about what those Modules do, we’ll see that soon, for now, imprint this much, OWIN is a blueprint and Katana in as implementation.
This article is published from the DNC .NET Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months. Subscribe to this eMagazine for Free
Why do we need OWIN?
With the vague idea of what is OWIN and Katana, let’s go deeper and see what is the grand scheme of things in which OWIN and Katana fit in. After all what is the OWIN specification for?
The Microsoft Web Application Stack today
We first take a step back and see how Web Applications work on ASP.NET today from a hosting point of view. Anyone webdev worth their salt, know that during development, you use either Cassini - the development web server, or IIS Express, the newer more robust in-process web server. But when we deploy our ASP.NET apps, it’s invariably on an IIS server. IIS is the be-all-end-all of ASP.NET Web Hosting at least from a production deployment stand point.
With IIS we know that we will get a set of extension points, but we will get things like Compression, Authentication, Static content serving etc. for free. All this making IIS one giant black box into which we immerse our ASP.NET application. We can visualize it as follows.
This looks like a pretty picture till we start thinking of using our application in scenarios without IIS. Do such scenarios exist? Well, recently we reviewed the Sitefinity CMS application and their demo was making innovative use of Cassini, they could have very well used an alternative if available. Think of application stacks like Pentaho and Jasper Reports in the Java world. They don’t depend on a preconfigured web server to work, they come bundled with a Web Server which could be Apache or could be something smaller and lighter.
So yes, scenarios do very much exist.
The grand scheme of OWIN and the Katana project
OWIN aims to change the above picture as follows
The OWIN spec splits the entire stack into four layers
1. Host
2. Server
3. Middleware
4. Custom Application
Katana as we briefly mentioned above is a suite being built, that will have its own OWIN compliant implementations of the Host, Server and Middleware layers. The difference (from IIS) being it will be far more granular giving you way more control on how to structure your application. The final goal being not to replace IIS but provide a suite of functionality that can be ‘assembled’ to comprise of only the pieces that you need for your application.
Thus the above diagram can also be considered as the ‘architecture’ for Katana. Now let’s look at each of these components in details.
Host
Hosts are near the OS, low level pieces of functionality that do things like
- Manage the underlying system processes
- Manage the server selection, lining up the OWIN modules and handling of requests.
Katana (the OWIN implementation from Microsoft) has (planned) support for three Hosting options.
a. IIS/ASP.NET: Via HttpModule and HttpHandler implementations, Katana manages to implement the OWIN pipeline requirements and execute OWIN compliant modules. This is managed by installing the Microsoft.AspNet.Host.SystemWeb Nuget package in any Web Application that you may be working on. There is one caveat though, IIS acts as both the Host and the Server, so when you use the Nuget package, you have to run with this ‘limitation’ and cannot swap in another Server implementation
b. Custom Host: This is a closer to the metal option that allows users to use a Console application, Windows Process or even a WinForms application to be the host. We will look at this option in a lot more details.
c. OwinHost.exe: This is another ‘implementation’ coming out of the Katana suite. This provides a little more support in terms of bootstrapping but providing a Console Host that starts an Http Server on its own so that you can focus on configuring the middleware and building the final application.
With the hosting sorted out, let’s move to the next layer that Katana has in store, which is the Server layer.
Server
Often the distinction of Host and Server is merged and the fact that the OWIN spec recognizes these two as separate entities, speaks to the granularity and pluggability OWIN is aiming to achieve. As a base implementation, the Katana project provides two Server implementation.
a. Microsoft.Owin.Host.SystemWeb: As mentioned above, the IIS/ASP.NET host module serves as both the Host and Server implementation under IIS/ASP.NET. As a result it’s quoted in both the categories.
b. Microsoft.Owin.Host.HttpListener: This is a more barebones implementation using the .NET Frameworks’ HttpListener class. It contains the plumbing required to open ports and channel requests to the requests in the OWIN pipeline/middleware. We will use this in our sample below.
This brings us to the crux or if we may say, Strength of the OWIN spec, the Middleware!
Middleware/OWIN Modules’ pipeline
As depicted in the diagram above, the pipeline of OWIN modules basically channel a request from the application to the server. This pipeline approach greatly modularizes the overall solution giving the end user ability to pick and choose components required. As we will see shortly, if we are building a static HTML site, then we need not include SignalR, WebAPI or Authentication. On the other hand, if we are building an MVC application, we can use framework like Fubu MVC or Nancy and ignore Web API as well as Microsoft’s MVC stack completely. Essentially, flexibility of having an HttpHost outside IIS opens up a plethora of permutations and combinations that are today possible only if you agree to bring along the overhead of a full blown Server like IIS.
At a very basic level, an OWIN Middleware Component must implement a Func that takes in an IDictionary or objects and returns a Task.
Func, Task>
Once you have you have a middleware component, you can wire them up as follows
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use(, );
}
}
Note the class name Startup and the method Configuration and its signature. This forms a convention for Katana Hosts. Each middleware tends to implement its own set of Extension methods for Use however for a Host and Server agnostic implementation, the above method signature must be implemented correctly.
Once all required middleware has been registered, we can then build Applications on top of this stack. In the next section, we will see how we can build an application using Katana OWIN components.
Building a SignalR App using Katana OWIN components
SignalR’s self-host story is built on Katana. The SignalR team went ahead and built a Server and the Middleware for themselves. Today we’ll build a Self-Hosted Console app using Katana components that not only hosts SignalR server, but also static HTML pages. In the end, we’ll have a crude chat application that uses Signal, HTML and JavaScript only. No WebForms or ASP.NET MVC involved.
The Console Host App
For the first part, we pretty much follow the instructions on SignalR’s Wiki, however as we will see, we go beyond the barebones instructions.
Step 1: We start off with a Windows Console Application and call it – SignalRSelfHost
Step 2: We pull in the dependencies required to build a self-hosting SignalR using Nuget
1. First up we get Owin Hosting: This has the WebApplication class that provides us the bootstrapping necessary to do ‘self-hosting’.
PM> Install-Package Microsoft.Owin.Hosting –pre
2. Next we get the Owin HttpListener
PM> Install-Package Microsoft.Owin.Host.HttpListener –pre
3. Finally we get SignalR’s Owin host implementation
PM> Install-Package Microsoft.AspNet.SignalR.Owin
Step 3: In the main method, add the following code to initialize our Host. We set the default url to localhost:9999. If there is a –url command line argument passed to the console application, we try to use that as the url for our self-hosted server.
Next we send the url and the Type Startup to the WebApplication class’ Start method. This starts off the Self host Server. If your Visual Studio is not running in Administrator mode, you may get an exception here because of lack of port opening permissions. Just start Visual Studio in Administrator mode.
Note: Startup is a naming convention that OwinHosts follow. We’ll see the Startup class shortly.
So finally our Console app code is as follows:
public class SignalRSelfHost
{
static string url = "http://localhost:9999";
static void Main(string[] args)
{
if (args.Contains("-url"))
{
url = GetUrl(args);
}
using (WebApplication.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
private static string GetUrl(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-url" && args.Length > i+1)
{
return args[i + 1];
}
}
return url;
}
}
Step 4: Next we add a new class called Startup.cs. The class name Startup and the method Configuration with an IAppBuilder input parameter as we saw is a convention that Katana looks out for, and uses to configure the MiddleWare modules.
In our implementation below, we see that we have created a (SignalR) HubConfiguration object with Cross Domain enabled and used the MapHubs extension method to pass the configuration to instantiate and pass the SignalR Hub middleware into the OWIN chain.
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Turn cross domain on
var config = new HubConfiguration { EnableCrossDomain = true };
// This will map out to http://localhost:9999/signalr
app.MapHubs(config);
}
}
At this point, we have SignalR hooked up but it doesn’t have a Hub associated with it. So let’s add a SignalR Hub next.
Step 5: We add a class called MyHub that has one function SendMessage and all it does is, lobs back the message it receives to all connected clients.
public class MyHub : Hub
{
public void Send(string message)
{
Clients.All.addMessage(message);
}
}
At this point, we have SignalR middleware and SignalR Hub ready to go. Only thing missing are clients. Just out of curiosity, if you run the application and navigate to the [server url]/signalr/hubs, your browser will download a JavaScript file for you. If we open the JS file, we’ll see it’s the JavaScript hub proxy and a proxy for our MyHub.Send method in it.
But how do we add an HTML/JavaScript Client? We could create a new ASP.NET application, but that would kind of defeat the whole purpose of the self-hosting effort. What if we could host static HTMLs along with the SignalR middleware, and build our clients in pure JavaScript?
This is where we realize the beauty of OWIN. We can actually use a Katana module that allows us to host plain HTML. Let’s see how.
Adding Static HTML Hosting to our Self-Hosted Application
Note: We are dealing with the ‘bleeding edge’ here as in most of the Katana Owin components are Beta or Alpha release. The Static HTML Hosting is an alpha release. So expect some tweaks when things go live late in 2013.
Step 1: We install Static HTML Hosting middleware module using Nuget as follows
PM> Install-Package Microsoft.Owin.StaticFiles –version 0.20-alpha-20220-88
It required some creative reverse engineering to get the StaticFiles package off Nuget.
Step 2: Once installed, we head back to the Startup class and add the highlighted code below
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HubConfiguration { EnableCrossDomain = true };
app.MapHubs(config);
string exeFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string webFolder = Path.Combine(exeFolder, "Web");
app.UseStaticFiles(webFolder);
}
}
This basically tells the Static Files host, that it should look for a folder called Web at the executable’s location and use all files under it for hosting.
Step 3: Create a folder named Web in the solution
Step 4: In the Web Folder, add a new HTML file called Home.html. This will be our web client but before we implement anything here, we need to get the SignalR dependencies in first.
Step 5: Let’s install the SignalR client side scripts from Nuget
PM> install-package Microsoft.AspNet.SignalR.JS
Notice it will get jQuery 1.6.x. This is rather old so we’ll upgrade jQuery to latest using the following command
PM> update-package jquery
This will install jQuery and SignalR clients to the Scripts folder at the Solution’s root. Once installed move the Scripts folder under the Web folder as follows:
Step 6: Select each file under Web folder (or its subfolders) and change the “Copy To Output Directory” property to ‘Copy Always”. This ensures all our changes are updated on each run.
Implementing the SignalR Client
Our plumbing for Static hosting is now complete. All that we have to do is implement a SignalR client. Let’s do a rudimentary message exchange sample. We will have two Text Boxes, one for incoming messages and one for outgoing messages. We’ll have one button to send the text, in the outgoing message textbox, to all connected clients. It isn’t very pretty as we can see below:
The markup for it is as follows:
SignalR Self Host
SignalR Self Hosting
It is rather un-remarkable except for the Magic script source of “../signalr/hubs”. This is the dynamic proxy that is generated at runtime, which maps to the server side hub.
The SignalR Implementation
The implementation is very simple:
· We retrieve an instance of the client side hub proxy.
· Add the addMessage Method to the hub’s client so that it can be invoked by the server
· Next we initialize the client connection. Once initialization is done (async), we assign an event handler for the button click. The handler function uses the hub’s server proxy to invoke the ‘Send’ method in our Hub. The hub on receipt lobs it back to all clients and the addMessage method is invoked on all of them. The complete script is as follows:
And we are done!!!
Demo
Let’s build the application and open a couple of browser instances. I have two IE10 browser instances open side by side. As I type in one and hit send, the message comes up in both the browsers simultaneously. Sweet!
Caveats
As I mentioned earlier, the Self hosting bits are pre-release as is the static hosting. I had some issues where sometimes the connections would be refused specially when using Firefox, so I dropped it from the demo. But these are all going to be fixed by the final release towards the end of this year.
Conclusion
This concludes our OWIN and Katana introduction with a walkthrough using SignalR and Static hosting middleware in the pipeline. We saw the granularity of control that we have when introducing features in our application’s stack. Just like we added SignalR and the Static hosting, we could also add Web API and then call Web API controllers from HTML pages using AJAX. Similarly if we put an Authentication module in front of the pipeline, we could put all requests behind an Authentication layer. However the biggest strength of the OWIN implementation is independence from IIS stack and granularity of control. Another aspect that we didn’t cover is the increase in testability, thanks to less monolithic pieces of infrastructure.
Download the entire source code from our GitHub repository at bit.ly/dncm7-swin
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Sumit is a .NET consultant and has been working on Microsoft Technologies since his college days. He edits, he codes and he manages content when at work. C# is his first love, but he is often seen flirting with Java and Objective C. You can follow him on twitter at @
sumitkm or email him at sumitkm [at] gmail