Building an Owin based web application Example

What if i tell you that you can built a web application that is

would you believe me? If not you should

Owin stands for - Open Web Interface for .NET its basically allows you to built a fast light weight host to run your applications. Link to more Owin explanations

Owin also allows you to have a direct access you every cycle an http request has to go through unlike technologies like asp.net web applications that need the IIS hosting services

Notice that Owin is a specification that defines the relation between a framework and a web server, and Katana is the implementation of Owin using Microsoft components , this components are referenced at the top of the program ,if you want to implement Owin on maybe Linux , you will have to use other implementation then Katana Link to Katana project

  1. using Microsoft.Owin.Hosting;
  2. using Owin;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace KatanaIntro
  10. {
  11.     using System.IO;
  12.     using System.Web.Http;
  13.     using AppFunc = Func<IDictionary<string, object>, Task>;
  14.  
  15.     class Program
  16.     {
  17.         static void Main(string[] args)
  18.         {
  19.             string uri = "http://localhost:6060";
  20.  
  21.             using (WebApp.Start<Startup>(uri))
  22.             {
  23.                 Console.WriteLine("Starting!");
  24.                 Console.ReadKey();
  25.                 Console.WriteLine("Stopping!");
  26.             }
  27.         }
  28.     }
  29.  
  30.     public class Startup
  31.     {
  32.         public void Configuration(IAppBuilder app)
  33.         {     
  34.             app.Use(async (environment, next) =>
  35.             {
  36.                 Console.WriteLine("Requesting : " + environment.Request.Path);
  37.  
  38.                 await next();
  39.  
  40.                 Console.WriteLine("Response: " + environment.Response.StatusCode);
  41.             
  42.             });
  43.  
  44.             app.UseHelloWorld();
  45.         }
  46.     }
  47.     public class MyappComponent
  48.     {
  49.         AppFunc _next;
  50.         public MyappComponent(AppFunc next)
  51.         {
  52.             _next = next;
  53.         }
  54.  
  55.         public Task Invoke(IDictionary<string, object> environment)
  56.         {
  57.             var response = environment["owin.ResponseBody"] as Stream;
  58.             using (var writer = new StreamWriter(response))
  59.             {
  60.                 return writer.WriteAsync("<b>Hello and welcome to my lightweight web server</b>");
  61.             }
  62.  
  63.         }
  64.     }
  65.  
  66.     public static class AppBuilderExtenions
  67.     {
  68.         public static void UseHelloWorld(this IAppBuilder app)
  69.         {
  70.             app.Use<MyappComponent>();   
  71.         }
  72.     }
  73.  
  74. }

This is a very simple demonstration of using Owin

what we have here is a consol application, notice that we do not use any IIS services and the only things we need to do are to reference the Katana components like Microsoft.Owin.Hosting and Owin through Nuget or other way, and run this application in a release or debug mode

after you have ran the application you need to open you web browser and go to http://localhost:6060 url

if all goes well you should see you consol application output looking like this:

...

here is the output of the consol application after you have typed the url on your web browser

...

here is the output of the browser after you have typed in the url

I will try to explain the code in short just to show the basic things that are going on, if you are interested in more information you can google for more Owin examples or ask me on the comment section below

  1. static void Main(string[] args)
  2.         {
  3.             string uri = "http://localhost:6060";
  4.  
  5.             using (WebApp.Start<Startup>(uri))
  6.             {
  7.                 Console.WriteLine("Starting!");
  8.                 Console.ReadKey();
  9.                 Console.WriteLine("Stopping!");
  10.             }
  11.         }

Because it is a consol application we need a main method, we define the the url that this application will listen to

in line 5 we basically start our server and let every body know that by printing "starting!"

using AppFunc = Func<IDictionary<string, object>, Task>;

in line 13 we define the AppFunc - this is how components (will see one later) process and interact with request to the server

it is a delegate to a function that takes a dictionary that represents the request environment and returns a task

in the environment you can find out every thing about the request and response to the client

The delegate returns a task to keep the Async behavior of the application(see my async and await topic for more info)

One important thing we must know before moving on is that Owin uses the pipeline model

this pipeline consists of different components (middlewares) that do not know about each other, one component can do the logging the other can check for authorization and the third one can be our component that writes our massage in the browser

Owin pipline

  1. public class MyappComponent
  2.   {
  3.       AppFunc _next;
  4.       public MyappComponent(AppFunc next)
  5.       {
  6.           _next = next;
  7.       }
  8.  
  9.       public Task Invoke(IDictionary<string, object> environment)
  10.       {
  11.           var response = environment["owin.ResponseBody"] as Stream;
  12.           using (var writer = new StreamWriter(response))
  13.           {
  14.               return writer.WriteAsync("<b>Hello and welcome to my lightweight web server</b>");
  15.           }
  16.  
  17.       }
  18.   }

lets look at our component that writes the massage to the browser, we call that component in line 44 in the big program

first we see a constructor that gets an appFunc element (next) that represents the next component in the pipeline and saves it in a privet appFunc variable(_next)

this constructor is must, if we don't add him we would get an exception because Katana uses reflection to search for it

this component must have this constructor because Katana needs to involve this component in to the pipeline

although we don't use the _next element our selfs, it is being used behind the scenes

Next, in the invoke function, we write the response in the response body using the environment dictionary

using a stream writer we can asynchronously write to that stream and return a task

public static class AppBuilderExtenions
  {
      public static void UseHelloWorld(this IAppBuilder app)
      {
          app.Use<MyappComponent>();   
      }
  }

here we create an extension to the appFunc element to include our function

most importantly we register our component to this application, this registration will form Katana to look for the invoke method in the component and instantiate the component and make it ready to use in the pipe line

The component we wrote also called a middleware because it seats in the middle of a processing pipeline, we can assume that they might be other components before or after ours, unlike our component, components may interact with one another

Now to our final and the most important piece of code that actually runs it all

  1. public class Startup
  2.   {
  3.       public void Configuration(IAppBuilder app)
  4.       {     
  5.           app.Use(async (environment, next) =>
  6.           {
  7.               Console.WriteLine("Requesting : " + environment.Request.Path);
  8.  
  9.               await next();
  10.  
  11.               Console.WriteLine("Response: " + environment.Response.StatusCode);
  12.           
  13.           });
  14.           app.UseHelloWorld();
  15.       }
  16.   }

here we actually have two middlewars, the one we saw before and the middlware in line 5

this middlware (component) is written in a higher abstraction and doesn't use a class

it uses the app.run function that takes a lambda expression, this lambda expression takes the environment and the next component and returns a task (the same idea as before)

this middlware is different form the previous "myAppCommponent" because of line 9 "await.next()"

await.next() means that we need to wait for the next middleware to finish its job

it is important to understand that every thing before the await.next() is done in the request pipeline and every thing after the await.next() is don in the respond pipeline

  1. we type in the url in the browser
  2. the request pipeline for starts for the default path
  3. the first middleware is writing the path: "/" (line 36)
  4. the first middleware is waiting for the next middleware to finish (myAppComponent)
  5. the second middlware (myAppComponent) writes to the browser (line 44)
  6. the request pipline is finished
  7. the respond pipe line begins
  8. the first middleware executes the lines that are after the await.next() and writes the status code - "Response: 200" (line 40)
  9. the response pipe line ends
  10. now, the browser sends a second request for the favorite icon to the path favicon.ico
  11. the request pipe line begins
  12. the path is written : "Requesting : /faveicon.ico"
  13. because our second middleware executes only on the default path it does not writes to the browser again
  14. the request pipeline ends
  15. the respond pipe line begins
  16. the status code 200 is written
  17. respond pipe line ends

these are the stages for one default path access, is possible to write middleware that respond to different paths by defining different routes for every middleware