If you start almost any new ASP.NET project in the new preview of Visual Studio 2013, you’ll find a reference to the Owin package inside. OWIN (the Open Web Interface for .NET) is a specification designed to decouple web servers from the frameworks and applications they host. The OWIN goal is to provide a lightweight, modular, and portable platform for mixing and matching components, frameworks, and servers.
Katana is Microsoft’s implementation of OWIN components. The code is available on CodePlex.
In a future post we can talk about how OWIN compares to System.Web, but first let’s get a simple example up and running from scratch.
In VS2013 you can start a new console mode application, then run the following commands in the package manager console:
install-package Microsoft.Owin.Hosting -IncludePreRelease install-package Microsoft.Owin.Host.HttpListener –IncludePreRelease install-package Microsoft.Owin.Diagnostics –IncludePreRelease install-Package Owin.Extensions -IncludePrerelease
Inside the Main entry point for the console application, we can use the WebApp class to start an HTTP listener.
static void Main(string[] args) { string uri = "http://localhost:8080/"; using (WebApp.Start<Startup>(uri)) { Console.WriteLine("Started"); Console.ReadKey(); Console.WriteLine("Stopping"); } }
The Startup class used as the generic type parameter to WebApp.Start is a class we’ll have to implement, too.
public class Startup { public void Configuration(IAppBuilder app) { app.UseWelcomePage(); } }
IAppBuilder is an interface we can use to compose the application for Katana to host. In this setup we’ll invoke the UseWelcomePage extension method provided by Microsoft.Owin.Diagnostics. Running the console program and pointing a browser to http://localhost:8080 produces:
Other extension methods allow for more fine grained control over the request and response processing. For example, UseHandlerAsync from Owin.Extensions allows for a more traditional “Hello, World” response to every request.
public class Startup { public void Configuration(IAppBuilder app) { app.UseHandlerAsync((req, res) => { res.ContentType = "text/plain"; return res.WriteAsync("Hello, World!"); }); } }
So far this doesn’t appear much different than self-hosting WebAPI in a console application, but in some future posts we’ll dig a little deeper into some examples showing the loftier goals of OWIN and Katana.