Reputation: 2613
Is there anyway I can do dynamic GZip compression from code, when the module is not installed on a IIS Server ? My hosting company does not want to install this module on the server, still waiting for a reason from them.
I checked locally it can help me allot when dynamic compression is allowed.
kind regards
Upvotes: 1
Views: 896
Reputation: 24558
You can achieve this using an action filter.
public class CompressFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
Add this attribute to the desired controllers
[CompressFilter]
public class HomeController : Controller
or as a global filter.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CompressFilter());
}
}
Note : for web ressources (Js & Css), I also highly suggest you to use bundling & minification.
Upvotes: 4