Getting an absolute URL from ASP.NET MVC

ASP.NET MVC 4 Comments

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;
}

public static string ActionAbsolute(this UrlHelper url, string actionName, string controllerName)
{
    return new Uri(GetBaseUrl(url), url.Action(actionName, controllerName)).AbsoluteUri;
}

4 Responses to “Getting an absolute URL from ASP.NET MVC”

  1. ASP.NET MVC Archived Blog Posts, Page 1 Says:
    January 13th, 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 [...]

  2. Getting an absolute URL from ASP.NET Webforms | Veggerby : IBlog Says:
    January 15th, 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 [...]

  3. Veggerby : IBlog » Blog Archive » ASP.NET MVC Gravatar HtmlHelper Says:
    September 30th, 2009 at 21:27

    [...] The Absolute extension method is similar to the ActionAbsolute method I posted earlier: [...]

  4. IanNo Gravatar Says:
    November 25th, 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!

Leave a Reply

Icons by N.Design Studio. Designed By Ben Swift. Powered by WordPress, Search Optimization and Free WordPress Themes
Entries RSS Comments RSS Log in