chamara
chamara

Reputation: 12711

Convert relative path to full URL

My main domain is http://redrocksoftware.com.au. i have an relative path to a file like /PDF/myfile.pdf

I need to convert this relative path into full URL. something like below.

http://redrocksoftware.com.au/PDF/myfile.pdf

i tried below but did not worked

VirtualPathUtility.ToAbsolute("/PDF/myfile.pdf")

Upvotes: 1

Views: 18742

Answers (4)

AHeine
AHeine

Reputation: 1

Return new System.Uri(Page.Request.Url, ResolveClientUrl("~/relative/path.aspx")).AbsoluteUri

Upvotes: 0

Steven de Salas
Steven de Salas

Reputation: 21447

The following extension method worked for me:

 public static class Extensions
 {
    /// <summary>
    /// Turns a relative URL into a fully qualified URL.
    /// (ie http://domain.com/path?query) 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="relativeUrl"></param>
    /// <returns></returns>
    public static string GetFullUrl(this HttpRequest request, string relativeUrl) {
        return String.Format("{0}://{1}{2}",
                        request.Url.Scheme,
                        request.Url.Authority,
                        VirtualPathUtility.ToAbsolute(relativeUrl));
    }
 }

Use it as follows:

 HttpContext.Current.Request.GetFullUrl("~/MyOtherPage.aspx");

Works with virtual directories too, and you dont need MVC.

Upvotes: 8

Kamil T
Kamil T

Reputation: 2216

You can use

string FullUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + "/PDF/MyFile.pdf"

It works in asp.net, I'm not sure about MVC, but it should work too.

Upvotes: 7

dtb
dtb

Reputation: 217233

You can use the Uri Class to combine an absolute URI and a relative path:

Uri absolute = new Uri("http://redrocksoftware.com.au/");
Uri result = new Uri(absolute, "/PDF/MyFile.pdf");
// result == {http://redrocksoftware.com.au/PDF/MyFile.pdf}

Upvotes: 8

Related Questions