HttpContext.Current.Response.Filter: response filter is invalid

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

he throws out HttpExceptionof

The response filter is invalid.

So my questions are:

1) How to set the filter to empty or the default filter?

2) Is it even necessary?

Thank you in advance for your help.

+4
source share
3 answers

check this message. Although this is about ASp.Net 3.5, I tried and it works. I just read the filter var filter = Response.Filterand then set it to nullResponse.Filter = null

+7
source

Except @Nileshs comment / answer (+1 to it since 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));
    }
}

:

HttpContext.Current.Response.Filter = new EmptyFilter(HttpContext.Current.Response);
0

Try to clear your solution and remove the old DLL (possibly renamed from renaming the project). It sorted it out for me.

0
source

Source: https://habr.com/ru/post/1532098/


All Articles