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:
I hope this helps :-)
Previous Entry: Domain name siphoning, how to protect a website
Latest entries:
Comments
My Links
Tags
Follow me
About
Powered by FoxBlog
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2011, Nathan Fox