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
In my opinion the easiest approach is to use the ability to conditionally branch the execution pipeline with
UseWhenExtensions.UseWhen
:Though I would argue that it should be just fine to enable it for all endpoints.
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:
GzipCompressionMiddleware.cs
Program.cs