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!
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.
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.
To use Compression Middleware, we'll create a custom middleware that adds compression capabilities to our ASP.NET application.
dotnet new webapi -n CompressionMiddlewareExample
cd CompressionMiddlewareExampledotnet add package Microsoft.AspNetCore.ResponseCompressionCompressionMiddleware: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.
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!");
});
}
}
}Let's create a simple API controller that returns a large amount of data to test our Compression Middleware.
ValuesController: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");
}
}
}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;
}
}
}dotnet runNavigate 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.
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.
What is Compression Middleware in ASP.NET?