Q:

ASP.NET MVC - Server cannot modify cookies after HTTP headers have been sent

I've an OnActionExecuted in my application controller that checks if the user is still logged in. When the user isn't logged in anymore the session needs to be destroyed and get redirected back to the homepage without going to the new page. (So the current request has to be cancelled).
This is my code:
if (System.Web.HttpContext.Current.Session.IsNewSession)
        {
            if (System.Web.HttpContext.Current.Session["Userid"] != null)
            {
                // Check userid session
                filterContext.Controller.TempData["sessionError"] = 1;
                System.Web.HttpContext.Current.Session.RemoveAll();
                System.Web.HttpContext.Current.Response.BufferOutput = true;
                System.Web.HttpContext.Current.Response.Flush();
                RedirectToAction("Index", "Home");
                return;
            }
        }

However the problem i get with this code is that it gives me an exception:
   Message:
Server cannot modify cookies after HTTP headers have been sent.

Source:
   at System.Web.HttpResponse.BeforeCookieCollectionChange()
   at System.Web.HttpCookieCollection.Add(HttpCookie cookie)
   at Topsite.Classes.GlobalFunctions.SetCookie(String name, String value, DateTime endDate)
   at Topsite.Controllers.ApplicationController.OnActionExecuted(ActionExecutedContext filterContext)
   at System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.<BeginInvokeAction>b__20()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult)

Any suggestions?
I did found some other questions that had the same problem, i followed them but still i received the exception. That's why i am asking for help.

A:

Doing so on OnActionExecuted is too late. 
You should take into consideration using the OnActionExecuting instead. 
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting(v=vs.118).aspx

