how to gzip content in asp.net MVC?
如何压缩由asp.net mvc应用程序发送的输出?
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
{...}
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
Eg
[CompressFilter]
public void Category(string name, int? page)
And as an added bonus, it also includes a CacheFilter
You can also increase the performance by using compression and caching for the response data. Have a look at the following link :-
http://weblogs.asp.net/rashid/asp-net-mvc-action-filter-caching-and-compression
链接地址: http://www.djcxy.com/p/42052.html