views:

46

answers:

2

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

+2  A: 

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

http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-compression.aspx

E.g.

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

And as an added bonus, it also includes a CacheFilter

veggerby
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??
Praveen Prasad
Use Firebug as in the article and look at response header
veggerby
+2  A: 

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

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.

jim
same concept :) almost identical code
veggerby
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
is is possible i can do some settings in web.config to do the compression. one more thing i want to know, how to check howmuch overhead is added to server by compression code we are running here.
Praveen Prasad
praveen- unfortunately, a web.config solution isn't one that i'm aware of (i also think it would be too course grained to be flexible). as for memory usage, i think you may have to use some tool outside of IIS to measure that.
jim