Server cannot attach a header after HTTP headers have been sent

Asked

Viewed 898 times

4

Good morning,

I have the following code that I use to compress the controllers using the GZip.

I log in to the system normally, but if I try to change registered company the following error is shown:

Server cannot attach a header after HTTP headers have been sent

Line error:

Response.AppendHeader("Content-Encoding", "gzip");

Code used for compression:

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace EngemanMVC.MLib
{
    /// <summary>
    /// Attribute that can be added to controller methods to force content
    /// to be GZip encoded if the client supports it
    /// </summary>
    public class CompressContentAttribute : ActionFilterAttribute
    {

        /// <summary>
        /// Override to compress the content that is generated by
        /// an action method.
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            GZipEncodePage();
        }

        /// <summary>
        /// Determines if GZip is supported
        /// </summary>
        /// <returns></returns>
        public static bool IsGZipSupported()
        {
            string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
            if (!string.IsNullOrEmpty(AcceptEncoding) &&
                    (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate")))
                return true;
            return false;
        }

        /// <summary>
        /// Sets up the current page or handler to use GZip through a Response.Filter
        /// IMPORTANT:  
        /// You have to call this method before any output is generated!
        /// </summary>
        public static void GZipEncodePage()
        {
            HttpResponse Response = HttpContext.Current.Response;

            if (IsGZipSupported())
            {
                string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];

                if (AcceptEncoding.Contains("gzip"))
                {
                    if (Response.Filter != null)
                    {
                        Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
                                                    System.IO.Compression.CompressionMode.Compress);
                        Response.Headers.Remove("Content-Encoding");
                        Response.AppendHeader("Content-Encoding", "gzip");
                    }
                }
                else
                {
                    if (Response.Filter != null)
                    {
                        Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
                                                System.IO.Compression.CompressionMode.Compress);
                        Response.Headers.Remove("Content-Encoding");
                        Response.AppendHeader("Content-Encoding", "deflate");
                    }
                }


            }

            // Allow proxy servers to cache encoded and unencoded versions separately
            Response.AppendHeader("Vary", "Content-Encoding");
        }
    }
}

Note: If I continue the program works normally, but I wanted to avoid putting an empty Try/catch because it is not recommended or beautiful.

Can someone help me?

  • Do you switch companies by redirecting the page? If so, what method do you use? Response.Redirect(url) or just Redirect(url) ?

  • The logout is simply a window.location.hreffor login, where when calling the controller action, Sesssions are cleared.

1 answer

1


The problem happens because when redirecting the page via window.location.hrefredirect is carried out on the page plus the request headers are maintained, what you should do is try before redirecting the page, is clear the request headers, when the page is loaded again it will come without the compression headers.

Probably the method window.location.href is running directly in the page code. As you put the ASP.NET MVC tag try instead of calling the relocation code on the page to use a method in the controller for redirection, more or less as described below:

public ActionResult Logout()
{
    Response.ClearHeaders();
    Response.AddHeader("Accept-Encoding", "gzip");
    Response.Redirect("/login");// Aqui vai a página para qual quer ser redirecionado
}

This way when the request goes to the other page it will have the headers cleaned. thus enabling the use of compression.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.