Buy eBooks and Videos in Just $5 – By Packt Publishing

Being an active participant in reviewing Packt Publishing books related to Software discipline, I would like to announce a “$5 eBook Bonanza”. It’s an exciting offer to buy any book or video in just $5.

Go to this link and buy as many as you can. This offer is valid till 6th Jan 2015.

Understanding OWIN by developing a custom OWIN middleware component

OWIN stands for Open Web Interface for .NET that decouples the Web Application from Web Server through an interface. In this article I will try to show some basic example of creating custom OWIN middle ware component and using it in self-host console application. The idea is to clarify the working of OWIN and what we can achieve with this new paradigm.

OWIN classifies web application into 4 parts

  1. Host
  2. Server
  3. Middleware
  4. Application
    ASP.Net MVC web application Fully OWIN compatible web applications
    Host IIS Any application Console App, Windows Service, IIS etc.
    Server IIS An application that hooks up the HTTP Listener to listen for a request.
    Middleware IHTTP Modules OWIN Middleware
    Application ASP.NET MVC 5 in IIS ASP.NET vNext, Web API 2 etc.

How is the request processed by OWIN Host?

When the request comes in to the OWIN server, the request properties like query string, path, content type, and so many others added into the IDictionary<string, object> object. This dictionary object is then sent to the request pipeline and then middleware components in the request pipeline can use this dictionary object and process accordingly.

OWIN expose following interface

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

Func is a new way of defining delegates in .NET framework. The first parameter denotes the input parameter and second as a return parameter. Here we have IDictionary<string,object> as input and Task as the resultant output.

When the request comes to the server, OWIN host calls the Invoke method of all the middleware components defined in order and pass the dictionary object. Each middleware component gets the complete request properties as dictionary object.

Startup.cs class is an entry point to build the request pipeline. In the Startup class, Configuration method is mandatory that takes IAppBuilder as a parameter. Using IAppBuilder you can add the OWIN based middleware and define the request pipeline. Developers can develop their own pipeline for incoming request. In IIS there are many components configured through which the request is passed through and for simple or mid-sized applications that seems to be an overkill. With OWIN based host it is quite easy to use only those OWIN extensions or middleware components that are required for your web application.

In order to elaborate, let’s create a simple OWIN middleware that logs the incoming request message into the console application and host the OWIN server in console application itself.

  1. Open Visual studio 2013 and create a new Console Application project
  2. Add OWIN NuGet references using NPM
  3. We need to add three NPM packages i.e.
    1. Microsoft.Owin – contains helper types and abstractions for simplifying the creation of OWIN components
    2. Microsoft.Owin.Host.HttpListener – OWIN server used for self-hosting
    3. Microsoft.Owin.Hosting– provides infrastructure types for hosting
  4. These libraries are part of Katana project, an implementation of OWIN by Microsoft
  5. In order to use OWIN on IIS, you can use Microsoft.Owin.Host.SystemWeb. Normally in IIS the request pipeline consists of HttpModules that are subscribes to events like BeginRequest, AuthenticateRequest etc. When you add this assembly in ASP.Net web applications you can define the OWIN based middle ware components in your Startup.cs and at runtime the Katana runtime mapped each of the middleware component to PreExecuteRequestHandler that corresponds to the PreRequestHandlerExecute event. Thus, the middleware components are invoked by the IIS integrated HTTP pipeline. This is not supported with classic HTTP pipeline.
  6. Once these references are added, we have to create a Startup.cs class and add Configuration method as below

    public void Configuration(IAppBuilder app){ }

7. Now let’s create a custom logging component to log incoming HTTP Request

      public class LoggingMiddleware

         {

              private AppFunc appFunc;

              public LoggingMiddleware(System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> func)

           {

                 this.appFunc = func;

            }

            public async Task Invoke(IDictionary<string,object> env)

{

                  Console.WriteLine(“Request method is “+ env[“owin.RequestMethod”]);

                  var task = appFunc.Invoke(env);

}

}

8. Add this logging middleware in the configuration method using IAppBuilder use method

public void Configuration(IAppBuilder app)

{

app.Use<LoggingMiddleware>();

}


9. In the Main method of console app start the server using following WebApp.Start

Microsoft.Owin.Hosting.WebApp.Start<Startup>(http://localhost:12345&#8221;);

Console.ReadLine();


Following is a complete code

     

public class Startup

{

public void Configuration(IAppBuilder app)

{

app.Use<LoggingMiddleware>();

}

}

public class LoggingMiddleware

{

private AppFunc appFunc;

public LoggingMiddleware(System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> func)

{

this.appFunc = func;

}

public async Task Invoke(IDictionary<string,object> env)

{

Console.WriteLine(“Request method is “+ env[“owin.RequestMethod”]);

var task = appFunc.Invoke(env);

}

}

class Program

{

static void Main()

{

Microsoft.Owin.Hosting.WebApp.Start<Startup>(http://localhost:12345&#8221;);

Console.ReadLine();

}

}

}

10. Now run the application and access the URL http://localhost:5555

11. You will see the logging on your console app.