Reputation: 44605
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?
Upvotes: 17
Views: 21756
Reputation: 31
This solution could work and is shorter:
string url = (new Uri(Request.Url, ".")).OriginalString;
Upvotes: 1
Reputation: 1
This should work
Request.Url.OriginalString.Substring(0, Request.Url.OriginalString.LastIndexOf(Request.FilePath.Substring(Request.FilePath.LastIndexOf("/")))) + "/"
Upvotes: 0
Reputation: 7797
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 );
Upvotes: 4
Reputation: 29304
This is what I use
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
Upvotes: 33