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
E.g.
[CompressFilter]
public void Category(string name, int? page)
And as an added bonus, it also includes a CacheFilter
veggerby
2010-09-27 09:08:20
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
2010-09-27 09:13:59
Use Firebug as in the article and look at response header
veggerby
2010-09-27 09:15:36
+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
2010-09-27 09:17:03
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
2010-09-27 09:31:42
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
2010-09-27 11:51:43
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
2010-09-27 14:35:50