HTTP Header Errors with MVC3 Redirects

Created 08 July 2011 16:03, updated 18 June 2017 13:29

We noticed in our error logs that we were getting quite a few of these good old errors:

"Cannot redirect after HTTP headers have been sent."
This wasn't affecting our system from a usability point of view, but it's irritating nonetheless. Anyway, the cause of the error was the following code in the OnActionExecuting override of a custom ActionFilterAttribute:
HttpContext.Current.Response.Redirect("our url", true)

Looks fine, right?

The error here is that within action filter attributes, you don't know what other code is being executed in the request pipeline – in our case we had a BaseController adding caching headers in the OnResultExecuting override. 

The correct way to do this is to set the result of the filterContext object – this gets dealt with immediately and the error goes away.  The correct code is:

filterContext.Result = new RedirectResult("our url");

Pretty trivial, I know, but I Googled this and found very little out there that actually describes this error and the solution.

bcscomputercity on 01 October 2011 at 15:00
Nice information.....thanks.<br /><a href="" rel="nofollow"></a>
Anonymous on 04 October 2011 at 21:46
This error doesn&#39;t happen on my develop machine(Win XP) and only happen on MVC3 + IIS7.<br /><br />The error msg is: <br />System.Web.HttpException (0x80004005): Cannot redirect after HTTP headers have been sent.<br /><br />Thanks.