C# extension methods for the HttpRequestBase class.

using System;
using System.Collections.Specialized;
using System.Runtime.CompilerServices;
using System.Web;

namespace Extensions
{
    public static class HttpRequestBaseExtensions
    {
        /// <summary>
        /// Get the Application root path.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        public static string ApplicationRoot(this HttpRequestBase instance)
        {
            string str = string.Concat(instance.Url.GetLeftPart(UriPartial.Authority), instance.ApplicationPath);
            if (str.EndsWith("/", StringComparison.Ordinal))
            {
                str = str.Substring(0, str.Length - 1);
            }
            return str;
        }

        /// <summary>
        /// Determines whether this instance can compress the specified instance.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns>
        ///     <c>true</c> if this instance can compress the specified instance; otherwise, <c>false</c>.
        /// </returns>
        public static bool CanCompress(this HttpRequestBase instance)
        {
            string upperInvariant = (instance.Headers["Accept-Encoding"] ?? string.Empty).ToUpperInvariant();
            if ((instance.Browser.MajorVersion >= 7 ? false : instance.Browser.IsBrowser("IE")))
            {
                return false;
            }
            if (upperInvariant.Contains("GZIP"))
            {
                return true;
            }
            return upperInvariant.Contains("DEFLATE");
        }

        public static bool IsAjaxRequest(this HttpRequest request)
        {
            return request.Headers["X-Requested-With"]
                          .Equals("XMLHttpRequest",
                                  StringComparison.OrdinalIgnoreCase);
        }
    }
}