ASP .NET Tutorial: Compression Middleware

beginner
10 min

ASP .NET Tutorial: Compression Middleware

Welcome to CodeYourCraft's comprehensive guide on Compression Middleware in ASP.NET! In this lesson, we'll explore how to optimize your applications by compressing responses and reducing bandwidth usage. Let's dive in!

What is Compression Middleware? šŸŽÆ

Compression Middleware is a technique in ASP.NET that enables you to compress the data being sent to clients, which can significantly reduce the size of responses and improve the performance of your web applications.

Why Compression Middleware Matters? šŸ“

Compression Middleware is crucial for delivering faster page loads and a better user experience, especially for applications with large amounts of data. By reducing the size of data being sent, your server can handle more requests and decrease the overall load time.

Getting Started with Compression Middleware šŸ’”

To use Compression Middleware, we'll create a custom middleware that adds compression capabilities to our ASP.NET application.

  1. First, let's create a new .NET Core project:
sh
dotnet new webapi -n CompressionMiddlewareExample cd CompressionMiddlewareExample
  1. Next, we'll add the required NuGet package:
sh
dotnet add package Microsoft.AspNetCore.ResponseCompression
  1. Now, let's create a custom middleware called CompressionMiddleware:
csharp
using System.IO; using System.Net.Compression; using Microsoft.AspNetCore.Http; namespace CompressionMiddlewareExample { public class CompressionMiddleware { private readonly RequestDelegate _next; public CompressionMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { if (!context.Response.ContentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase) && context.Response.ContentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase)) { context.Response.OnStarting(() => { context.Response.EnableCompression(); return Task.CompletedTask; }); } await _next(context); } } }

šŸ“ Note: This middleware checks if the content type is not HTML or text-based and if it's eligible for compression. If it is, it enables compression on the response.

  1. Now, let's add the Compression Middleware to the pipeline:
csharp
using Microsoft.AspNetCore.Builder; namespace CompressionMiddlewareExample { public class Startup { public void ConfigureServices(IServiceCollection services) { // Nothing to do here. } public void Configure(IApplicationBuilder app) { app.UseMiddleware<CompressionMiddleware>(); app.Run(async context => { await context.Response.WriteAsync("Hello, World!"); }); } } }

Putting Compression Middleware to the Test šŸ’”

Let's create a simple API controller that returns a large amount of data to test our Compression Middleware.

  1. First, create a new API controller called ValuesController:
csharp
using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Text; namespace CompressionMiddlewareExample.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { [HttpGet("large-data")] public ActionResult<string> GetLargeData() { var data = Enumerable.Range(1, 1000000).Select(i => i.ToString()).Aggregate((a, b) => a + b + Environment.NewLine); return Content(data, "text/plain"); } } }
  1. Now, let's create an extension method to measure the response size:
csharp
using Microsoft.AspNetCore.Http; namespace CompressionMiddlewareExample { public static class HttpResponseExtensions { public static int GetContentLength(this HttpResponse response) { var length = response.ContentLength; if (length < 0) { using (var reader = new StreamReader(response.Body, Encoding.UTF8)) { length = (int)reader.BaseStream.Length; } } return length; } } }
  1. With the extension method in place, you can now test the API:
sh
dotnet run

Navigate to http://localhost:5000/api/values/large-data, and you'll see the large data being returned. To test compression, install a tool like Postman and compare the response sizes with and without compression enabled.

Wrapping Up āœ…

In this lesson, we've explored Compression Middleware in ASP.NET and learned how to implement it in our applications to optimize performance and reduce bandwidth usage. With the knowledge you've gained, you can now create more efficient web applications that provide a better user experience.

Quick Quiz
Question 1 of 1

What is Compression Middleware in ASP.NET?