Dumitru Chirutac
Dumitru Chirutac

Reputation: 637

Absolute URLs not working with Virtual Directories?

I created several virtual directors and I want to be able to get the url from the current http request.

For example:

http://www.site.com/app_1/default.aspx ===> http://www.site.com/app_1/

http://www.site.com/app_2/default.aspx ===> http://www.site.com/app_2/

....

http://www.site.com/app_n/default.aspx ===> http://www.site.com/app_n/

My code:

    string urlApp = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
    urlApp = urlApp.Substring(0, urlApp.LastIndexOf('/') + 1);

and I tried

    string urlApp = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/";

In localhost works great: http://localhost:2468/test.aspx result http://localhost:2468/

, but when access via virtual directory http://myhost/app_1/test.aspx result http://myhost/

how can i get http://myhost/app_1/?

Upvotes: 2

Views: 1671

Answers (1)

Mel Padden
Mel Padden

Reputation: 1003

HttpContext.Current.Request.ApplicationPath 

is what you need to get the route to your virtual directory. Append it to the URL you've already gotten and you're onto a winner. Something like

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

Should work, but look out for trailing slashes.

Upvotes: 5

Related Questions