Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get app relative url from Request.Url.AbsolutePath

Tags:

c#

asp.net

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

VirtualPathUtility seems to only work with ~/XXX urls?

like image 512
jgauffin Avatar asked Mar 14 '12 11:03

jgauffin


4 Answers

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

like image 65
Ashwin Singh Avatar answered Sep 29 '22 13:09

Ashwin Singh


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); 
like image 41
jgauffin Avatar answered Sep 29 '22 13:09

jgauffin


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());
like image 27
ccook Avatar answered Sep 29 '22 13:09

ccook


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.

like image 28
Stjepan Rajko Avatar answered Sep 29 '22 15:09

Stjepan Rajko