skip to Main Content

I have a .NET core project (EntityRelationship) and enable the Gzip compressor for that project.

Program.cs

using EntityRelationship.Data;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using System.IO.Compression;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

...

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
    options.Providers.Add<GzipCompressionProvider>();
});

builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal;
});


var app = builder.Build();

...

// Enable compression
app.UseResponseCompression();

app.Run();

In this case, the Compressor enable for whole endpoints in this project.

But I try to enable the compressor for specific endpoints.

How to implement?

I try to enable the compressor for specific endpoints.

How to implement?

2

Answers


  1. In my opinion the easiest approach is to use the ability to conditionally branch the execution pipeline with UseWhenExtensions.UseWhen:

    Conditionally creates a branch in the request pipeline that is rejoined to the main pipeline.

    app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments(...), // predicate to determine that compression should be used 
        appCond => appCond.UseResponseCompression());
    

    Though I would argue that it should be just fine to enable it for all endpoints.

    Login or Signup to reply.
  2. I’m using middleware and it works fine. And I also try the solution provided by
    Guru Stron and not works for me. You also can find the commented code in my Program.cs file.

    My Test Result like below:

    enter image description here

    GzipCompressionMiddleware.cs

    using System.IO;
    using System.IO.Compression;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder.Extensions;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc.Filters;
    
    namespace gzip
    {
        public class GzipCompressionMiddleware 
        {
            private readonly RequestDelegate _next;
            public GzipCompressionMiddleware(RequestDelegate next)
            {
                _next = next;
            }
            public async Task InvokeAsync(HttpContext context)
            {
                if (context.Request.Path == "/Home/Privacy")
                {
                    var acceptEncoding = context.Request.Headers["Accept-Encoding"];
    
                    if (acceptEncoding.ToString().Contains("gzip"))
                    {
                        context.Response.Headers.Add("Content-Encoding", "gzip");
    
                        using (var gzipStream = new GZipStream(context.Response.Body, CompressionMode.Compress))
                        {
                            context.Response.Body = gzipStream;
    
                            await _next(context);
    
                            await gzipStream.FlushAsync();
                        }
                    }
                    else
                    {
                        await _next(context);
                    }
                }
                else
                {
                    await _next(context);
                }
            }
        }
        
    }
    

    Program.cs

    using Microsoft.AspNetCore.ResponseCompression;
    
    namespace gzip
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var builder = WebApplication.CreateBuilder(args);
    
                //builder.Services.AddResponseCompression(options =>
                //{
                //    options.EnableForHttps = true;
                //    options.Providers.Add<GzipCompressionProvider>();
                //});
    
                // Add services to the container.
                builder.Services.AddControllersWithViews();
    
                var app = builder.Build();
    
                // Configure the HTTP request pipeline.
                if (!app.Environment.IsDevelopment())
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
    
                // Enable compression
                //app.UseResponseCompression();
    
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseMiddleware<GzipCompressionMiddleware>();
    
                //app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/Home/Privacy"), // predicate to determine that compression should be used 
                //   appOptIn => appOptIn.UseResponseCompression());
    
                app.UseAuthorization();
    
                app.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
    
                // Enable compression
                //app.UseResponseCompression();
    
                app.Run();
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search