get main part of url including virtual directory
21,343
Solution 1
This is what I use
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
Solution 2
Request.Url should contain everything you need. At that point it's a matter of checking the string, and what you prefer to grab from it. I've used AbsoluteUri before, and it works.
This example isn't fool proof, but you should be able to figure out what you need from this:
string Uri = Request.Url.AbsoluteUri;
string Output = Uri.Substring(0, Uri.LastIndexOf('/') + 1 );
Solution 3
This solution could work and is shorter:
string url = (new Uri(Request.Url, ".")).OriginalString;
Author by
amateur
Updated on February 21, 2020Comments
-
amateur over 4 years
I am working with .net 4.0 c#.
I want to be able to get the url from the current http request, including any virtual directory. So for example (request and sought value):
http://www.website.com/shop/test.aspx -> http://www.website.com/shop/
http://www.website.com/test.aspx -> http://www.website.com/
http://website.com/test.aspx -> http://website.com/
How is it possible to achieve this?
-
Doozer Blake over 12 yearsHttpContext.Current.Request.ApplicationPath won't return /shop/ in their first example if it's not the root of the application.
-
Marek Karbarz over 12 yearsIt's a good point IF 'shop' is not a virtual directory. I guess I went with the assumption that it was based on amateur's question. So the question then becomes does amateur want the full path to the root of the application (what my code provides) or just the full url minus the file name.
-
Doozer Blake over 12 yearsNow that I re-read the question, they do just say virtual directory, So your answer does fit the question specifically.