Create absolute URLs using ASP.NET MVC

I recommend

At times it is desirable to create an absolute URL for a HTML element's href or src attribute. I failed to find a shrink wrapped mechanism to generate them in ASP.NET MVC, and some of the methods I found on the web were not quite what I wanted. So I created extension methods for the Uri class, which will generate absolute URLs relative to the current context's Request.Url property.

The class definition follows:

public static class UriHelperExtensions
   // Prepend the provided path with the scheme, host, and port of the request.
   public static string FormatAbsoluteUrl(this Uri url, string path)
      return string.Format( 
         "{0}/{1}", url.FormatUrlStart(), path.TrimStart('/') );

   // Generate a string with the scheme, host, and port if not 80.
   public static string FormatUrlStart(this Uri url)
      return string.Format( "{0}://{1}{2}", url.Scheme, 
         url.Host, url.Port == 80 ? string.Empty : ":" + url.Port );

The following snippet of code from an ASP.NET MVC Razor view demonstrates how to generate an absolute URL given the relative URL /images/img.jpg.

   <img src="@Request.Url.FormatAbsoluteUrl("/images/img.jpg")" alt="Alt text" />

For my blog, the HTML generated for the img element will be:

   <img src="" alt="Alt text" />

I hope this helps :-)

Technical ASP.NET .NET ASP.NET MVC January 25, 2012

comments powered by Disqus