Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 251
HarshSharma Avatar asked Jan 12 '23 12:01

HarshSharma


1 Answers

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:

  • How to redirect from OnActionExecuting in Base Controller?
  • ASP.NET MVC : Response.Redirect(url, TRUE) does not stop request processing
like image 150
artokai Avatar answered Jan 14 '23 02:01

artokai