Middleware does not have access to MVC constructs or context. ASP.NET Core 1.1 introduced middleware as MVC filters, providing access to the MVC constructs and context for middleware components.
- [Instructor] The final middleware update in 1.1 is the ability to use middleware as MVC filters. And the advantage here is that filters have access to the MVC context and constructs, and using middleware as a filter provides the same access to the middleware. Now, they run in the same stage as resource filters, which is before model binding and after the rest of the pipeline. To do this, we create a custom class with a Configure method, and then we add to the controller or action the MiddlewareFilter attribute, calling the type of this class.
So let's look at this in code. So here I have a custom class called MyMiddleWareItem, and I have my Configure method that takes an IapplicationBuilder as its only parameter. And then you would do whatever you need to do to create your middleware. Now, to keep the example simple, I'm just going to add in response compression. So I have applicationBuilder.UseResponseCompression, and that way I can specifically target certain areas for compression.
To get this sample to run, we need to leave the services.AddResponseCompression in the configure services because that adds it into the dependency injection container. But we're going to want to turn it off in the configure method, as I've done here, so that we don't have it on application wide. Otherwise, we won't be able to see the effect of having it target a specific controller. In the ProductsController, I've un-commented line 10, which uses the MiddlewareFilter attribute, passing in the typeof MyMiddlewareItem, which is the custom class.
I already have this running, so let's look at how it works in Fiddler, and so let's first go to the home page where we do not have the attribute applied. We'll go ahead and execute and look at the response, and see it's plain text. We go into the headers, we're still cacheing, but it is not compressed. Go back to the composer, and lets call a method on the ProductController, and we execute this, we see the size is much smaller.
We see that it is compressed, and we go into the header, and sure enough the content encoding on the response is gzip. So this shows a very simple way that you can target specific controllers or actions, if you wanted to get onto that level, with Middleware, but as an MVC filter.
- Running and debugging ASP.NET Core applications
- Pros and cons of migrating existing applications to ASP.NET Core.
- Built-in dependency injection
- Environment awareness and app configuration
- Web host configuration and SSL
- View components invoked as tag helpers
- Configuration and logging
- Using Razor Pages