Skip to content

How-To Create Katana Middleware

Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.

Learn more about Software Architecture & Design.
Join thousands of developers getting weekly updates to increase your understanding of software architecture and design concepts.

PipelineWhat 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.
context is of type IOwinContextnext 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.
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.
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.
Now when I run the application and make a HTTP call to http://localhost:8080, the headers returned are: owin

Source Code

GithubThe 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.
  1. How to Self Host ASP.NET Web Api

  2. Self Host ASP.NET Web Api as a Windows Service

  3. ASP.NET Self Host Static File Server

4 thoughts on “How-To Create Katana Middleware”

  1. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1930

  2. Pingback: 25-08-2015 - Links - Magnus Udbjørg

Leave a Reply

Your email address will not be published. Required fields are marked *