To use a Middleware with Litium we can create a startup class that inherits the IOwinStartupConfiguration interface and use it to insert a middleware into the OWIN pipeline.
A middleware is, put simply, a piece of code which can read information about the current request and add information to the response. And it’s a good place to put code that doesn’t really fit into controllers or services where we need to examine every request.
The example below will examine every request that comes into a Litium site. We are looking for a specific querystring and we want to store its value as a cookie. This is a real life example, but it has been modified and simplified.
This is tested with Litium 5 and 7 but probably works in more versions.
For the sake of simplicity this post will not take any project standards into consideration. But feel free to use the comments to suggest changes or improvements.
1. Creating a startup class
Since I’m using a fresh install of the Accelerator for demonstration purposes and not doing this in a customer project I’m just going to put this class in the Litium.Accelerator.Mvc root folder. Your project structure will probably be different depending on your project standards.
Start by adding a new class called Startup.cs and let this class inherit and implement IOwinStartupConfiguration. Then we would have a class that looks like this:
2. Creating a middleware
Create a new folder in the Litium.Accelerator project called Middleware and create a class called UtmCampaign.cs. Let this class inherit from OwinMiddleWare and implement that abstract class. (You need to install the nuget package Microsoft.Owin).
The UtmCampaign.cs class will now look like this:
3. Adding logic to the middleware
For this example I want to save the campaign name sent by different ad campaigns into a cookie. (I could then use this value when communicating with other third party services, which I have done for some customers, but we won’t cover that in this tutorial).
The UtmCapaign.cs middleware will now look like this:
4. Adding the middleware to the owin pipline
Lets go back to Startup.cs and add the middleware we just created to the owin pipeline like this:
And if I now browse to http://accelerator.localtest.me/?utm_campaign=asdf I can see that my middleware is put to use and has created a cookie for me:
5. Other uses of IOwinStartupConfiguration
The IOwinStartupConfiguration class isn’t only to used register your own middlewares. You can also use it to, for example, setup signalR if you want to use that on your Litium site.
You can also use it to configure external login providers such as facebook or Google