Skip to main content

Gets the site URL for the current ASP.NET application.

using System.Web;

namespace Helpers
{
    public static class UrlHelper
    {
        /// <summary>
        /// Gets the full ASP.NET application base URL.
        /// </summary>
        /// <returns>The full qualified application base URL.
        /// (ex: http(s)://example.com/</returns>
        public static string GetAppBaseUrl()
        {
            var appPath = string.Empty;

            var context = HttpContext.Current;
            if (context != null)
            {
                appPath = string.Format("{0}://{1}{2}{3}",
                    context.Request.Url.Scheme,
                    context.Request.Url.Host,
                    context.Request.Url.Port == 80 ? string.Empty : string.Format(":{0}", context.Request.Url.Port),
                    context.Request.ApplicationPath);
            }

            return VirtualPathUtility.AppendTrailingSlash(appPath);
        }
    }
}