Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.Response.Filter: Response filter is not valid

Tags:

c#

asp.net

Busy with some legacy code to write to csv/xls:

// Set up response
string filename = "ErrorControlExport";
string attachment = "attachment; filename=" + filename + "_" + DateTime.UtcNow.ToFileTime() + "." + extension;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Pragma", "public");
// Clear any settings (such as GZip)
HttpContext.Current.Response.Filter = null;//exception occurs here

// Add BOM to force recognition of UTF-8
byte[] bom = new byte[] { 0xef, 0xbb, 0xbf };
HttpContext.Current.Response.BinaryWrite(bom);

However when the code reaches:

// Clear any settings (such as GZip)
HttpContext.Current.Response.Filter = null;//exception occurs here

it throws a HttpException of

Response filter is not valid.

So my questions are:

1) How do I set the filter to an empty or default filter?

2) Is it even necessary?

Thanks in advance for your help

like image 472
David Kroukamp Avatar asked Mar 17 '14 08:03

David Kroukamp


2 Answers

check this post. Even though it talks about ASp.Net 3.5, I tried it and it works. I just read the filter var filter = Response.Filter and then assigned null to it Response.Filter = null

like image 106
Nilesh Avatar answered Nov 16 '22 06:11

Nilesh


Besides @Nileshs' comment/answer (+1 to it as I used this method)

Another option is to create an Empty filter:

/// <summary>
/// Creates and empty filter for HttpResponse.Filter (i.e no proessing is done on the text before writting to the stream)
/// </summary>
class EmptyFilter : MemoryStream
{
    private string source = string.Empty;
    private readonly Stream filter;


    public EmptyFilter(HttpResponse httpResponseBase)
    {
        this.filter = httpResponseBase.Filter;
    }


    public override void Write(byte[] buffer, int offset, int count)
    {
        this.source = Encoding.UTF8.GetString(buffer);

        this.filter.Write(Encoding.UTF8.GetBytes(this.source), offset, Encoding.UTF8.GetByteCount(this.source));
    }
}

than simply set to:

HttpContext.Current.Response.Filter = new EmptyFilter(HttpContext.Current.Response);
like image 42
David Kroukamp Avatar answered Nov 16 '22 05:11

David Kroukamp