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.
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.
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.
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:
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.
-
How to Self Host ASP.NET Web Api
-
Self Host ASP.NET Web Api as a Windows Service
-
ASP.NET Self Host Static File Server
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1930
Pingback: 25-08-2015 - Links - Magnus Udbjørg
Thanks Derek, exactly what I needed!
Glad this helped!