Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to compress .ashx content?

Tags:

c#

asp.net

In my web application I use an ashx file to write a file to the browser. I've noticed that there's no compression over the .ashx file, but only over my .aspx files.

Is it possible to compress .ashx? And if it is possible, how?

Currently I use global.asax to handle the compression:

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>

<script runat="server">
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
    HttpApplication app = sender as HttpApplication;
    string acceptEncoding = app.Request.Headers["Accept-Encoding"];
    Stream prevUncompressedStream = app.Response.Filter;

    if (!(app.Context.CurrentHandler is Page ||
        app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
        app.Request["HTTP_X_MICROSOFTAJAX"] != null)
        return;

    if (acceptEncoding == null || acceptEncoding.Length == 0)
        return;

    acceptEncoding = acceptEncoding.ToLower();

    if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
    {
        // defalte
        app.Response.Filter = new DeflateStream(prevUncompressedStream,
            CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "deflate");
    } else if (acceptEncoding.Contains("gzip"))
    {
        // gzip
        app.Response.Filter = new GZipStream(prevUncompressedStream,
            CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "gzip");
    }
}
</script>

This compresses about everything except my .ashx files. Who can help me?

SOLUTION

Because I created an .ashx file I automatically created a new type (my case ViewMht). This type didn't come through the first if statement:

    if (!(app.Context.CurrentHandler is Page ||
        app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
        app.Request["HTTP_X_MICROSOFTAJAX"] != null)
        return;

As you can see only files which inherit from 'Page' are compressed, and my ashx file is not of type Page. So I added a condition and now it works just fine:

if (!(app.Context.CurrentHandler is Page ||
      app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler" ||
      app.Context.CurrentHandler is ViewMht // This is the type I had to add
      ) ||
      app.Request["HTTP_X_MICROSOFTAJAX"] != null)
        return;
like image 836
Martijn Avatar asked Jun 02 '10 15:06

Martijn


1 Answers

If your compression is done on Global.asax then you need to place the code of the compression here to tell you what you need to change on your program.

Probably there is a check on the file extention.

like image 143
Aristos Avatar answered Sep 22 '22 02:09

Aristos