Setting Response.Filter after Response.Redirect can cause a Filtering is not allowed HttpException / by Matt Wrock

I ran into this error on a RequestReduce bug and there was not a whole lot of information pointing to a cause and remedy. So I’m posting this in the hopes that it will help the Google Lords find a solution more quickly for others.

So if you are using Razor templates in Asp.Net and you issue a Response.Redirect at some point either in the template itself or from a method that the template calls like Html.RenderAction for example, and then you later set a response  filter by calling Response.Filter, you will receive an HttpException stating “Filtering is not allowed.” It may look a little like this friendly message:

System.Web.HttpException (0x80004005): Filtering is not allowed.at System.Web.HttpResponse.set_Filter(Stream value)at RequestReduce.Module.RequestReduceModule.InstallFilter(HttpContextBase context) in c:\RequestReduce\RequestReduce\Module\RequestReduceModule.cs:line 223at System.Web.HttpApplication.SendResponseExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

For example, consider this Razor page:

@{    Layout = null;}

<!DOCTYPE html>

<html><head runat="server">    <title>index</title></head><body>    <div>@{ Html.RenderAction("Redirect"); }    </div></body></html>

Now assume we have a very simple action method like this:

public ActionResult Redirect(){    Response.Redirect("/Home/target");    return View();}

Ok. That’s kind of silly code but this is just to illustrate an example. And besides, who doesn’t like to be silly sometimes. Now it so happens that You have an HttpModule that sets a Response Filter. Here is what you should do:

if(!Response.IsRequestBeingRedirected)    Response.Filter = myFilter;

If you neglect to use the If statement checking for a redirect, you will be sorry. Unless of course you enjoy a white background with black text inside yellow boxes.

While my encounter to this has been with Razor templates and this does not reproduce using Web Forms views, I would still check for redirects before setting a Response Filter in any context. There is no reason that I can think of to ever filter a response that is being redirected.