C# extension methods for the HttpRequestBase class. Includes methods to get the web application's root path, check whether or not the client response can be compressed, and a method to determine Ajax request types.

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>
        public static string ApplicationRoot(this HttpRequestBase instance)
        {
            string applicationPath = instance.Url.GetLeftPart(UriPartial.Authority) + instance.ApplicationPath;

            // Remove the last /
            if (applicationPath.EndsWith("/", StringComparison.Ordinal))
            {
                applicationPath = applicationPath.Substring(0, applicationPath.Length - 1);
            }

            return applicationPath;
        }

        /// <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);
        }
    }
}