Example Abstract BaseHttpHandler

This example class is an abstract HttpHandler, to be used as a starting point for a HttpHandler.


namespace BaseHttpHandlerExample
{
    public abstract class BaseHttpHandler : IHttpHandler
    {
        public abstract bool RequiresAuthentication { get; }

        public abstract string ContentMimeType { get; }

        private static bool RequiresCompression
        {
            get
            {
                if (ConfigurationManager.AppSettings["UseGzip"] != null)
                    return Convert.ToBoolean(ConfigurationManager.AppSettings["UseGzip"]);

                return true;
            }
        }

        #region IHttpHandler Members

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ClearHeaders();
            context.Response.ClearContent();

            SetResponseCachePolicy(context.Response.Cache);

            if (!ValidateParameters(context))
            {
                RespondInternalError(context);
                return;
            }

            if (RequiresAuthentication
                && !context.User.Identity.IsAuthenticated)
            {
                RespondForbidden(context);
                return;
            }

            context.Response.Charset = "utf-8";
            context.Response.ContentEncoding = Encoding.UTF8;

            context.Response.ContentType = ContentMimeType;

            string fullContent = HandleRequest(context);


            if (RequiresCompression)
            {
                string compressionType = GetCompressionType(context);

                if (compressionType == "gzip")
                {
                    using (MemoryStream stream = new MemoryStream())
                    {
                        using (
                            StreamWriter writer = new StreamWriter(new GZipStream(stream, CompressionMode.Compress),
                                                                   Encoding.UTF8))
                        {
                            writer.Write(fullContent);
                        }
                        byte[] buffer = stream.ToArray();

                        WriteBytes(buffer, context, compressionType);
                    }
                }
                else if (compressionType == "deflate")
                {
                    using (MemoryStream stream = new MemoryStream())
                    {
                        using (
                            StreamWriter writer = new StreamWriter(new DeflateStream(stream, CompressionMode.Compress),
                                                                   Encoding.UTF8))
                        {
                            writer.Write(fullContent);
                        }
                        byte[] buffer = stream.ToArray();

                        WriteBytes(buffer, context, compressionType);
                    }
                }
                else
                {
                    //no compression plain text...

                    byte[] buffer = Encoding.UTF8.GetBytes(fullContent);

                    context.Response.AddHeader("Content-Length", buffer.Length.ToString());
                    context.Response.Write(fullContent);
                    context.Response.End();
                }
            }
            else
            {
                //no compression plain text...
                byte[] buffer = Encoding.UTF8.GetBytes(fullContent);

                context.Response.AddHeader("Content-Length", buffer.Length.ToString());

                context.Response.AddHeader("Content-encoding", "");

                context.Response.Write(fullContent);
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }

        #endregion

        public abstract string HandleRequest(HttpContext context);

        public abstract bool ValidateParameters(HttpContext context);

        public virtual void SetResponseCachePolicy
            (HttpCachePolicy cache)
        {
            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetNoStore();
            cache.SetExpires(DateTime.MinValue);
        }

        protected void RespondFileNotFound(HttpContext context)
        {
            context.Response.StatusCode
                = (int) HttpStatusCode.NotFound;
            context.Response.End();
        }

        protected void RespondInternalError(HttpContext context)
        {
            // It's really too bad that StatusCode property
            // is not of type HttpStatusCode.
            context.Response.StatusCode =
                (int) HttpStatusCode.InternalServerError;
            context.Response.End();
        }

        protected void RespondForbidden(HttpContext context)
        {
            context.Response.StatusCode
                = (int) HttpStatusCode.Forbidden;
            context.Response.End();
        }

        private static string GetCompressionType(HttpContext context)
        {
            string compressionType = "none";
            string encodingTypes = context.Request.Headers["Accept-Encoding"];

            if (!string.IsNullOrEmpty(encodingTypes))
            {
                encodingTypes = encodingTypes.ToLower();
                if (context.Request.Browser.Browser == "IE")
                {
                    if (context.Request.Browser.MajorVersion < 6)
                    {
                        compressionType = "none";
                    }
                    else if (context.Request.Browser.MajorVersion == 6 &&
                             !string.IsNullOrEmpty(context.Request.ServerVariables["HTTP_USER_AGENT"]) &&
                             context.Request.ServerVariables["HTTP_USER_AGENT"].Contains("EV1"))
                    {
                        compressionType = "none";
                    }
                }
                if (encodingTypes.Contains("gzip") || encodingTypes.Contains("x-gzip") ||
                    encodingTypes.Contains("*"))
                {
                    compressionType = "gzip";
                }
                else if (encodingTypes.Contains("deflate"))
                {
                    compressionType = "deflate";
                }
            }
            return compressionType;
        }


        private static void WriteBytes(byte[] bytes, HttpContext context, string compressionType)
        {
            HttpResponse response = context.Response;

            response.AddHeader("Content-Length", bytes.Length.ToString());

            response.AddHeader("Content-encoding", compressionType);

            response.OutputStream.Write(bytes, 0, bytes.Length);

            response.End();
        }
    }
}

You can download the Abstract BaseHttpHandler here



Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.