Middleware filter in ASP.NET Core

Posted by Anuraj on Friday, October 28, 2016

C# ASP.NET Core Middleware filter Middleware

This post is about a new feature in ASP.NET MVC, Middleware filter. Middleware typically sits in the global request handling pipeline. If you want to apply middleware to a specific controller or action method, you can use this feature. This feature only available with ASP.NET Core MVC 1.1. Long back I created a middleware (HTML Minification Middleware), which helps to minify generated HTML of an action. After few days I got a request to implement configuration options, which helps to exclude certain actions from minification. Now I can use Middleware filters instead of configuring the options.

To use middleware as a filter you first create a type with a Configure method that specifies the middleware pipeline that you want to use. I am not sure about the naming conventions, I just followed the one provided by Microsoft.

using Microsoft.AspNetCore.Builder;
public class HtmlMinificationPipeline
{
    public void Configure(IApplicationBuilder applicationBuilder)
    {
        applicationBuilder.UseHTMLMinification();
    }
}

Now you can use this type in specific controller class or action methods like this.

[MiddlewareFilter(typeof(HtmlMinificationPipeline))]
public class HomeController : Controller
{
}

or

public class HomeController : Controller
{
    [MiddlewareFilter(typeof(HtmlMinificationPipeline))]
    public IActionResult Index()
    {
        return View();
    }
}

MiddlewareFilter attribute is only available, if you are using ASP.NET Core MVC 1.1.

You can find more features and details about ASP.NET Core 1.1 Preview 1 release here

Happy Programming :)


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



MVP
Subscribe
Archives


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub