MVC2 ActionFilterAttribute - During OnActionExecuting Don't use Redirect Use RedirectResult
Still haven't upgraded to the visual studio 2010 RTM, so I'm talking about version RC1 of MVC2(the one that shipped with VS2010 RC),
But i guess this is also the case with the RTM version.
We followed the excellent post by Rob Conery and implemented our own ActionFilterAttribute
to validate that only authenticated users gain access to some of the actions.
At OnActionExecuting we checked for anonymous users and redirected them to the login page.
All went well till Accidentally i stumbled upon an exception right before the user was redirected to the login page,
users will never see this exception, but the server will suffer.
i usually check the "Remember Me" checkbox to save time...
(it is always a good idea to check the "Thrown" checkbox for the "Common Language Runtime Exceptions"
at the Exceptions window => click on Ctrl+Alt+e to open it).
It turns out that calling filterContext.HttpContext.Response.Redirect(loginUrl, true);
will redirect to the requested Url, but it doesn't stop the Action execution,
so the Action is called and also the OnActionExecuted(of the controller) event is called.
In my case i had an exception at one of the actions trying to get some user data,
and then an exception at OnActionExecuted where i set expiration headers on the request
(got the"Server cannot append header after HTTP headers have been sent.").
The solution:
Use filterContext.Result = new RedirectResult(sUrl); instead of the redirect.
this will skip the Action and of course redirect to the Url.
Note that although the requested Action was skipped, OnActionExecuted will be executed,
but the filterContext.Canceled property will be set to true so you can stop unwanted execution inside it as well
hope this helps.