What I love about Katana (OWIN Implementation) is the ability to add functionality through the request pipeline. In this post I’m going to extend my ASP.NET Self Host Web Api application by demonstrating how you can create your own Katana Middleware.

What’s OWIN Middleware?

OWIN specification defines middleware as:

Middleware – Pass through components that form a pipeline between a server and application to inspect, route, or modify request and response messages for a specific purpose.

Katana IAppBuilder.Use

There are couple different ways you can create your own middleware. The simplest is to call the IAppBuild.Use method in your Startup class.

For our example, we are going to add a Product to the response header.

View the code on Gist.

context is of type IOwinContext, next is of Func<Task>

IOwinContext contains the Request, Response, Environment and other properties you can access to manipulate the request or response.

Middleware Type

Another way to create middlware is by creating your own class that extends and overrides the OwinMiddleware base class.

For this example, we are going to add a MachieName to the response header.

View the code on Gist.

In order to include our new middleware class into the pipleline, you must call the IAppBuilder.Use in your Startup class, but this time specifying the type of our class.

View the code on Gist.

Notice we aren’t passing an instance of our CustomMiddlware but just the type.

Startup Class

After adding our two new middlware that are adding headers to the response, here is what our Startup class now looks like.

View the code on Gist.

Now when I run the application and make a HTTP call to http://localhost:8080, the headers returned are:

Source Code

The source code for this demo is available on Github.

OWIN/Katana Series

If you want more information about OWIN/Katana, please take a look at my other series of posts.