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?
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.
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.
is of type IOwinContext
is of Func<Task>
IOwinContext contains the Request, Response, Environment and other properties you can access to manipulate the request or response.
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.
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:
The source code
for this demo is available on Github.
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