amateur
amateur

Reputation: 44605

get main part of url including virtual directory

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

Answers (4)

Oscar
Oscar

Reputation: 31

This solution could work and is shorter:

string url = (new Uri(Request.Url, ".")).OriginalString;

Upvotes: 1

This should work

Request.Url.OriginalString.Substring(0, Request.Url.OriginalString.LastIndexOf(Request.FilePath.Substring(Request.FilePath.LastIndexOf("/")))) + "/"

Upvotes: 0

Doozer Blake
Doozer Blake

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

Marek Karbarz
Marek Karbarz

Reputation: 29304

This is what I use

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;

Upvotes: 33

Related Questions