I have been in situations where I need to generate an absolute URL to a specific action in an ASP.NET MVC application. The main problem mostly lies in getting the “domain” part of the URL. The only way to do this is to examine the request URL. I came across a very nice method of doing this during an encounter with the dotnetopenid.
public static Uri GetBaseUrl(this UrlHelper url)
{
Uri contextUri = new Uri(url.RequestContext.HttpContext.Request.Url, url.RequestContext.HttpContext.Request.RawUrl);
UriBuilder realmUri = new UriBuilder(contextUri) { Path = url.RequestContext.HttpContext.Request.ApplicationPath, Query = null, Fragment = null };
return realmUri.Uri;
}
{
Uri contextUri = new Uri(url.RequestContext.HttpContext.Request.Url, url.RequestContext.HttpContext.Request.RawUrl);
UriBuilder realmUri = new UriBuilder(contextUri) { Path = url.RequestContext.HttpContext.Request.ApplicationPath, Query = null, Fragment = null };
return realmUri.Uri;
}
public static string ActionAbsolute(this UrlHelper url, string actionName, string controllerName)
{
return new Uri(GetBaseUrl(url), url.Action(actionName, controllerName)).AbsoluteUri;
}
ASP.NET · ASP.NET MVC · url

ASP.NET MVC Archived Blog Posts, Page 1 · January 13, 2009 at 17:44
[...] to VoteGetting an absolute URL from ASP.NET MVC (1/12/2009)Monday, January 12, 2009 from blog.veggerby.dkI have been in situations where I need to generate an [...]
Getting an absolute URL from ASP.NET Webforms | Veggerby : IBlog · January 15, 2009 at 20:33
[...] to the post Getting an absolute URL from ASP.NET MVC here is the corresponding ASP.NET Webforms version (not as extension methods): public static Uri [...]
Veggerby : IBlog » Blog Archive » ASP.NET MVC Gravatar HtmlHelper · September 30, 2009 at 21:27
[...] The Absolute extension method is similar to the ActionAbsolute method I posted earlier: [...]
Ian · November 25, 2009 at 19:54
public static string ActionAbsolute(this UrlHelper url, string actionName, string controllerName, object routeValues)
{
return new Uri(
GetBaseUrl(url),
url.Action(actionName, controllerName, routeValues)
).AbsoluteUri;
}
Thanks again!