How do I turn a relative URL into a full URL?

This is probably explained more easily with an example. I’m trying to find a way of turning a relative URL, e.g. “/Foo.aspx” or “~/Foo.aspx” into a full URL, e.g. http://localhost/Foo.aspx. That way when I deploy to test or stage, where the domain under which the site runs is different, I will get http://test/Foo.aspx and http://stage/Foo.aspx.

Any ideas?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Have a play with this (modified from here)

public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) {
    return string.Format("http{0}://{1}{2}",
        (Request.IsSecureConnection) ? "s" : "", 
        Request.Url.Host,
        Page.ResolveUrl(relativeUrl)
    );
}

Method 2

This one’s been beat to death but I thought I’d post my own solution which I think is cleaner than many of the other answers.

public static string AbsoluteAction(this UrlHelper url, string actionName, string controllerName, object routeValues)
{
    return url.Action(actionName, controllerName, routeValues, url.RequestContext.HttpContext.Request.Url.Scheme);
}

public static string AbsoluteContent(this UrlHelper url, string path)
{
    Uri uri = new Uri(path, UriKind.RelativeOrAbsolute);

    //If the URI is not already absolute, rebuild it based on the current request.
    if (!uri.IsAbsoluteUri)
    {
        Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
        UriBuilder builder = new UriBuilder(requestUrl.Scheme, requestUrl.Host, requestUrl.Port);

        builder.Path = VirtualPathUtility.ToAbsolute(path);
        uri = builder.Uri;
    }

    return uri.ToString();
}

Method 3

You just need to create a new URI using the page.request.url and then get the AbsoluteUri of that:

New System.Uri(Page.Request.Url, "Foo.aspx").AbsoluteUri

Method 4

This is my helper function to do this

public string GetFullUrl(string relativeUrl) {
    string root = Request.Url.GetLeftPart(UriPartial.Authority);
    return root + Page.ResolveUrl("~/" + relativeUrl) ;
}

Method 5

I thought I’d share my approach to doing this in ASP.NET MVC using the Uri class and some extension magic.

public static class UrlHelperExtensions
{
    public static string AbsolutePath(this UrlHelper urlHelper, 
                                      string relativePath)
    {
        return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
                       relativePath).ToString();
    }
}

You can then output an absolute path using:

// gives absolute path, e.g. https://example.com/customers
Url.AbsolutePath(Url.Action("Index", "Customers"));

It looks a little ugly having the nested method calls so I prefer to further extend UrlHelper with common action methods so that I can do:

// gives absolute path, e.g. https://example.com/customers
Url.AbsoluteAction("Index", "Customers");

or

Url.AbsoluteAction("Details", "Customers", new{id = 123});

The full extension class is as follows:

public static class UrlHelperExtensions
{
    public static string AbsolutePath(this UrlHelper urlHelper, 
                                      string relativePath)
    {
        return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
                       relativePath).ToString();
    }

    public static string AbsoluteAction(this UrlHelper urlHelper, 
                                        string actionName, 
                                        string controllerName)
    {
        return AbsolutePath(urlHelper, 
                            urlHelper.Action(actionName, controllerName));
    }

    public static string AbsoluteAction(this UrlHelper urlHelper, 
                                        string actionName, 
                                        string controllerName, 
                                        object routeValues)
    {
        return AbsolutePath(urlHelper, 
                            urlHelper.Action(actionName, 
                                             controllerName, routeValues));
    }
}

Method 6

Use the .NET Uri class to combine your relative path and the hostname.
http://msdn.microsoft.com/en-us/library/system.uri.aspx

Method 7

This is the helper function that I created to do the conversion.

//"~/SomeFolder/SomePage.aspx"
public static string GetFullURL(string relativePath)
{
   string sRelative=Page.ResolveUrl(relativePath);
   string sAbsolute=Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,sRelative);
   return sAbsolute;
}

Method 8

Simply:

url = new Uri(baseUri, url);

Method 9

In ASP.NET MVC you can use the overloads of HtmlHelper or UrlHelper that take the protocol or host parameters. When either of these paramters are non-empty, the helpers generate an absolute URL. This is an extension method I’m using:

public static MvcHtmlString ActionLinkAbsolute<TViewModel>(
    this HtmlHelper<TViewModel> html, 
    string linkText, 
    string actionName, 
    string controllerName, 
    object routeValues = null,
    object htmlAttributes = null)
{
    var request = html.ViewContext.HttpContext.Request;
    var url = new UriBuilder(request.Url);
    return html.ActionLink(linkText, actionName, controllerName, url.Scheme, url.Host, null, routeValues, htmlAttributes);
}

And use it from a Razor view, e.g.:

 @Html.ActionLinkAbsolute("Click here", "Action", "Controller", new { id = Model.Id })

Method 10

Ancient question, but I thought I’d answer it since many of the answers are incomplete.

public static string ResolveFullUrl(this System.Web.UI.Page page, string relativeUrl)
{
    if (string.IsNullOrEmpty(relativeUrl))
        return relativeUrl;

    if (relativeUrl.StartsWith("/"))
        relativeUrl = relativeUrl.Insert(0, "~");
    if (!relativeUrl.StartsWith("~/"))
        relativeUrl = relativeUrl.Insert(0, "~/");

    return $"{page.Request.Url.Scheme}{Uri.SchemeDelimiter}{page.Request.Url.Authority}{VirtualPathUtility.ToAbsolute(relativeUrl)}";
}

This works as an extension of off Page, just like ResolveUrl and ResolveClientUrl for webforms. Feel free to convert it to a HttpResponse extension if you want or need to use it in a non-webforms environment. It correctly handles both http and https, on standard and non-standard ports, and if there is a username/password component. It also doesn’t use any hard coded strings (namely ://).

Method 11

Here’s an approach. This doesn’t care if the string is relative or absolute, but you must provide a baseUri for it to use.

    /// <summary>
    /// This function turns arbitrary strings containing a 
    /// URI into an appropriate absolute URI.  
    /// </summary>
    /// <param name="input">A relative or absolute URI (as a string)</param>
    /// <param name="baseUri">The base URI to use if the input parameter is relative.</param>
    /// <returns>An absolute URI</returns>
    public static Uri MakeFullUri(string input, Uri baseUri)
    {
        var tmp = new Uri(input, UriKind.RelativeOrAbsolute);
        //if it's absolute, return that
        if (tmp.IsAbsoluteUri)
        {
            return tmp;
        }
        // build relative on top of the base one instead
        return new Uri(baseUri, tmp);
    }

In an ASP.NET context, you could do this:

Uri baseUri = new Uri("http://yahoo.com/folder");
Uri newUri = MakeFullUri("/some/path?abcd=123", baseUri);
//
//newUri will contain http://yahoo.com/some/path?abcd=123
//
Uri newUri2 = MakeFullUri("some/path?abcd=123", baseUri);
//
//newUri2 will contain http://yahoo.com/folder/some/path?abcd=123
//
Uri newUri3 = MakeFullUri("http://google.com", baseUri);
//
//newUri3 will contain http://google.com, and baseUri is not used at all.
//

Method 12

Modified from other answer for work with localhost and other ports… im using for ex. email links. You can call from any part of app, not only in a page or usercontrol, i put this in Global for not need to pass HttpContext.Current.Request as parameter

            /// <summary>
            ///  Return full URL from virtual relative path like ~/dir/subir/file.html
            ///  usefull in ex. external links
            /// </summary>
            /// <param name="rootVirtualPath"></param>
            /// <returns></returns>
            public static string GetAbsoluteFullURLFromRootVirtualPath(string rootVirtualPath)
            {

                return string.Format("http{0}://{1}{2}{3}",
                    (HttpContext.Current.Request.IsSecureConnection) ? "s" : ""
                    , HttpContext.Current.Request.Url.Host
                    , (HttpContext.Current.Request.Url.IsDefaultPort) ? "" : ":" + HttpContext.Current.Request.Url.Port
                    , VirtualPathUtility.ToAbsolute(rootVirtualPath)
                    );

            }

Method 13

In ASP.NET MVC, you can use Url.Content(relativePath) to convert into absolute Url


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x