HarshSharma
HarshSharma

Reputation: 660

server cannot set status after http headers have been sent

I have OnActionExecuting ActionFilter in which i have checked whether the user session has been expired or not, and in case when the session is expired, then the user must be redirected to the Login Page.

CompressFilterAttribute.cs file has the code as shown below:

public override void OnActionExecuting(ActionExecutingContext FilterContext)
{
    if (((((System.Web.Mvc.ControllerContext)(FilterContext)).HttpContext).Request).IsAuthenticated)
            GZipEncodePage(); //Function to check Session Expiration Time

            var action = (string)FilterContext.RouteData.Values["action"];

            if (!FilterContext.HttpContext.User.Identity.IsAuthenticated && 
                action != "Index" && 
                action != "FindStoreNameByText" && 
                action.ToLower() != "sessiontimeout" && 
                action.ToLower() != "logout")
            {
                string UrlSucesso = "/Home";
                string UrlRedirecionar = string.Format("?ReturnUrl={0}", UrlSucesso);
                string UrlLogin = FormsAuthentication.LoginUrl + UrlRedirecionar;
                FilterContext.HttpContext.Response.Redirect(UrlSucesso, true);
            }
    }

CustomErrorHandleAttribute.cs file has the code as shown below:

public override void OnException(ExceptionContext filterContext)
{
    base.OnException(filterContext);
    // Rest logic
}

In CustomErrorHandleAttribute.cs file I am getting the error --> server cannot set status after http headers have been sent

Please help me on this.

Upvotes: 4

Views: 19348

Answers (1)

artokai
artokai

Reputation: 405

Your OnActionExecution method sends the necessary redirection http headers, but It does not stop the controller code from executing.

I think you should use the following to redirect the user instead of Response.Redirect:

 FilterContext.Result = new RedirectResult(url); 

See also these other stack overflow questions:

Upvotes: 9

Related Questions