How-To Create Katana Middleware

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

ASP.NET Self Host Static File Server

Continuing in my Owin and Katana series of blog posts, I’m going to demo an ASP.NET Self Host Static File Server. If you have not seen my previous posts in this series, I’ve covered how to self host a Web Api application and how to use Topshelf to debug and run as a windows service.

The wonderful thing about the shift to Owin and Katana with ASP.NET is middleware.

Katana has a file server implementation that you can plugin to your application startup pipeline in order to serve static files either on a filesystem or from embedded resources.

Middleware

The first thing we will do with our demo application is install the Owin StaticFiles middlware into our project.

Install-Package Microsoft.Owin.StaticFiles

The simplest possible configuration is to call IAppBuilder.UseFileServer(true).  This will enable directory browsing of files from the current location of the executable.

When running our demo application, this results in showing us the directory listing when we pass thru our Web API routes without a match.

staticfiles1

Now this isn’t very useful but it displays the simplicity of different Owin middlewares that are available.

UseFileServer has several different overloads:

Name Description
System_CAPS_pubmethodSystem_CAPS_static UseFileServer(IAppBuilder)

Enable all static file middleware (except directory browsing) for the current request path in the current directory.

System_CAPS_pubmethodSystem_CAPS_static UseFileServer(IAppBuilder, Boolean)

Enable all static file middleware on for the current request path in the current directory.

System_CAPS_pubmethodSystem_CAPS_static UseFileServer(IAppBuilder, FileServerOptions)

Enable all static file middleware with the given options

System_CAPS_pubmethodSystem_CAPS_static UseFileServer(IAppBuilder, String)

Enables all static file middleware (except directory browsing) for the given request path from the directory of the same name

For our demo application, we are going to create our File Server to serve files from an Assets directory that lives in the same location as our executable.

Now when we browse we see the files within the Assets directory.

staticfiles2

Content Type Provider

The Katana FileServer only serves known content types.  If you try and browse to a file that is not a known content type, it will return a 404.

In my example above, I’ve added a data.json file.  Odd to me was that a json file is not a known content type.  In order to serve json files, we must create our own content type provider and add our mappings.

Now we need to specify our CustomContentProvider in our FileServerOptions.

Source Code

GithubThe source code for this demo is available on Github.


Self Host ASP.NET Web Api as a Windows Service

In my previous blog I demonstrated how to Self Host ASP.NET Web API, which was a very basic console application leveraging Owin and Katana.

The next step in this series is how to turn your console application into a Windows service.

If you have any questions, please follow me on Twitter.

Video

If you prefer a video tutorial, here is one I published to YouTube outlining a similar example as on this post.

Windows Service Template

The typical way to create a Windows Service is by using the Windows Service template when creating a new project within Visual Studio.

The template will create a Program.cs calling ServiceBase.Run() in the Main() method.

SelfHostServiceBase is the code that will extend ServiceBase.   You would have to implement OnStart() and OnStop()

That’s simplest possible implementation.  Now when you start debugging, you are treated with this wonderful message.

service

What this means is you must build your Windows service, start it, then attach the debugger to the process.

Doesn’t sound like a fun way to debug does it?

Topself

TopshelfThere is a great open source project called Topshelf which allows you to create a windows service which is much easier to debug.

Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.

First thing is to install Topshelf into your project via nuget.

Install-Package Topshelf

Next we need a tiny bit of code to configure our service with topshelf.

We tell topself which class will contain our service (TopselfService) as well as which method to call when the service starts and stops.

Also, you can define which user the service should run as, as well as the name, display name and description.

Now when you debug the application, it will run just like a Console application, in which you can add breakpoints and debug.

Self Host ASP.NET Web API

To verify my web api application is responding, here is the result from my Postman call

Postman

 

2-hour Video Course for $30 USD

Sign up for more info!

* indicates required




 

Source Code

GithubThe source code for this demo is available on Github.

Next…

Next up I’ll continue adding to the demo by serving static assets from your self host application.