34

How can I get the application relative url from Request.Url.AbsolutePath?

VirtualPathUtility seems to only work with ~/XXX urls?

jgauffin
  • 99,844
  • 45
  • 235
  • 372

7 Answers7

36

Its a little late to answer but there is a elegant solution to this. You can use

Request.Url.PathAndQuery

This will return the relative path of the page.

For example, if the URL is www.example.com/products?A=a&B=b&C=c, the above piece of code will return /products?A=a&B=b&C=c

Ashwin Singh
  • 7,197
  • 4
  • 36
  • 55
18

I solved it like this:

// create an absolute path for the application root
var appUrl = VirtualPathUtility.ToAbsolute("~/");

// remove the app path (exclude the last slash)
var relativeUrl = HttpContext.Current.Request.Url.AbsolutePath.Remove(0, appUrl.Length - 1);
Pankaj
  • 9,749
  • 32
  • 139
  • 283
jgauffin
  • 99,844
  • 45
  • 235
  • 372
9

This worked for me:

VirtualPathUtility.MakeRelative("~", Request.Url.AbsolutePath)

For example if the root of the website is /Website and Request.Url.AbsolutePath is /Website/some/path this will return some/path.

Stjepan Rajko
  • 876
  • 8
  • 9
9

To do this without using string manipulation and handling the application's relative path I used:

    var relativeUrl = VirtualPathUtility.ToAppRelative(
        new Uri(context.Request.Url.PathAndQuery, UriKind.Relative).ToString());
ccook
  • 5,869
  • 6
  • 56
  • 81
  • 1
    Why the `new Uri(context.Request.Url.PathAndQuery, UriKind.Relative).ToString()`? Isn't just `context.Request.Url.PathAndQuery` the same thing? – MiMo Dec 15 '16 at 21:27
4

I think this is the cleanest way:

new Uri(Request.Url.PathAndQuery, UriKind.Relative))
John Gibb
  • 10,603
  • 2
  • 37
  • 48
1

To build on Ashwin Singh's nice answer - I needed the anchor link to be included with my relative URL, so I just re-added it at the end:

Request.Url.PathAndQuery + Request.Url.Fragment

So http://localhost:8080/abc/d?foo=bar#jazz becomes /abc/d?foo=bar#jazz.

Ian Grainger
  • 5,148
  • 3
  • 46
  • 72
1
 String appUrl = VirtualPathUtility.ToAbsolute("~/");
 String RelativePath = new System.Uri(Page.Request.Url, "").PathAndQuery.Substring(appUrl.Length-1)
Pankaj
  • 9,749
  • 32
  • 139
  • 283