Middleware Filters in ASP.Net Core

In ASP.Net Core, Middlewares are configured and executed as part of global request pipeline and are executed on every Controller action execution. Starting with ASP.Net Core, we can apply middlewares to specific controllers and actions. In this tutorial, we are going to see how to use middlewares as filters on specific controller actions.

NOTE: Updated this tutorial on 2/27/2017 with MSBuild based Dotnet SDK.

Create an ASP.Net Core Application using VS 2017. I am using following version of Dotnet SDK which is based on MSBuild/CSProj (remember that previous versions of ASP.Net Core are based on Project.json/XProj.).

image

The MiddlewareFilter runs after AuthorizationFilter and before Model Binding and other Action filters.

Lets configure Response compression, add the below package. Now lets assume that we want to fire our compression middleware only on Index action but not on About Action.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <PropertyGroup>
    <PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="1.0.0-preview1-final" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
  </ItemGroup>

</Project>

Create a middle pipeline object as shown below.

public class CustomPipeline
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseResponseCompression();
    }
}

Configure the service as shown below.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
    services.AddResponseCompression(options =>
    {
        options.Providers.Add<GzipCompressionProvider>();
    });
    // Add framework services.
    services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Now lets configure Controller Actions as shown below.

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

    public IActionResult About()
    {
        ViewData["Message"] = "Contact Us";
        return View();
    }
}

Run the application using dotnet run. For Index page, we should see Content-Encoding header in Response headers.

image
Now when we navigate to About page, we should not see the Content-Encoding header.

image

That’s it for now, Happy Coding and Stay Tuned!!!

You may also like...