42

how to compress the output send by an asp.net mvc application??

2

3 Answers 3

94

Here's what i use (as of this monent in time):

using  System.IO.Compression;

public class CompressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
        if (string.IsNullOrEmpty(encodingsAccepted)) return;

        encodingsAccepted = encodingsAccepted.ToLowerInvariant();
        var response = filterContext.HttpContext.Response;

        if (encodingsAccepted.Contains("deflate"))
        {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
        else if (encodingsAccepted.Contains("gzip"))
        {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        }
    }
}

usage in controller:

[Compress]
public class BookingController : BaseController
{...}

there are other varients, but this works quite well. (btw, i use the [Compress] attribute on my BaseController to save duplication across the project, whereas the above is doing it on a controller by controller basis.

[Edit] as mentioned in the para above. to simplify usage, you can also include [Compress] oneshot in the BaseController itself, thereby, every inherited child controller accesses the functionality by default:

[Compress]
public class BaseController : Controller
{...}
16
  • actually, looked at your example - very similar indeed - spooky :). i've been using this code for over a year, so can verify that it works very well ...
    – jim tollan
    Commented Sep 27, 2010 at 9:31
  • 9
    I added it as a global filter, in my startup class I added GlobalFilter.Filters.Add(new CompressionAttribute()); and it works #1! Also inverted the if clause to make sure gzip is used instead of deflate when both encodings are supported. Commented Jan 14, 2015 at 18:52
  • 2
    Just wanted to add, that in case you didn't start by deriving from a base controller, don't be scared. You can always use an IoC container that will handle that. For example, in Ninject (MVC 5) you can use: "kernel.BindFilter<CompressAttribute>(FilterScope.Controller, 0);" under the "RegisterServices(IKernel kernel)" method!
    – Jose A
    Commented Oct 3, 2015 at 17:46
  • 1
    Great answer. But why you put deflate option first, I change order so gzip is first and now give around 10% more compresion Commented Sep 9, 2016 at 13:49
  • 1
    Important! You should check response.Filter for null before putting it in stream! I encountered issue, when locally everything is OK, but when deployed to Azure service it fails. Commented Jan 11, 2019 at 17:42
4

Have a look at this article which outlines a nifty method utilizing Action Filters.

For example:

[CompressFilter]
public void Category(string name, int? page)

And as an added bonus, it also includes a CacheFilter.

3
  • okie, testing this, one more thing i want to know , how can i check whether the data iam getting from server is gzipped or not?? Commented Sep 27, 2010 at 9:13
  • Use Firebug as in the article and look at response header
    – veggerby
    Commented Sep 27, 2010 at 9:15
  • 1
    Not working on MVC5, IIS 8.5 and .Net 4.5, any help will be appreciated.
    – aadi1295
    Commented Jul 21, 2015 at 12:34
3

For .NET Core 2.1 there is a new package that can be used ( Microsoft.AspNetCore.ResponseCompression )

Simple sample to get going, after installing the package:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCompression();

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

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseResponseCompression();
    }
}

You can read more about it here: https://learn.microsoft.com/en-us/aspnet/core/performance/response-compression?view=aspnetcore-2.1&tabs=aspnetcore2x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.