MVC 3 String Extension Methods for Absolute URLs

Below are two great helpers, I use them in my Email templates…

 public static class UrlHelperExtension
    {
        public static string AbsoluteAction(this UrlHelper url, string action, string controller, object routeValues)
        {
            var requestUrl = url.RequestContext.HttpContext.Request.Url;

            if (requestUrl == null)
                return null;

            var absoluteAction =
                string.Format("{0}{1}",
                    requestUrl.GetLeftPart(UriPartial.Authority),
                    url.Action(action, controller, routeValues));

            return absoluteAction;
        }

        public static string AbsoluteContent(this UrlHelper url, string contentUrl)
        {
            var requestUrl = url.RequestContext.HttpContext.Request.Url;

            if (requestUrl == null)
                return null;

            return  string.Format("{0}{1}",
                    requestUrl.GetLeftPart(UriPartial.Authority),
                    url.Content(contentUrl));
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>