Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in create an absolute (fully qualified) url from a relative path such as "~/page.aspx" given the current URL?

Tags:

c#

url

asp.net

Scenario is I have a application relative url like "~/path/to/page.aspx?query=string". I need to programatically create a web request to that page and currently using WebRequest.Create. The problem is WebRequest.Create requires a fully qualified url including the protocol/domain/port etc.

I have access to the current Request.Url object but there doesn't seem to be an easy way to get just the base url keeping the protocol (HTTP vs HTTPS) as well as any port numbers as well as the path to the application.

I mean all the info there, so if need be I could just take all the parts and combine them but it seems like it might be error prone and it would be great to have something built-in that's well tested to do the job. Page.ResolveUrl gets me almost there, but it's missing the protocol and the domain/port.

like image 838
Davy8 Avatar asked Dec 08 '10 17:12

Davy8


1 Answers

Try System.Web.VirtualPathUtility.ToAbsolute(). I've used that (albeit in VB.NET, but I'm sure there's a C# equivalent) with a great deal of success. It can even translate just a base virtual path (i.e. System.Web.VirtualPathUtility.ToAbsolute("~") will turn into the base url of your app).

EDIT

How about Request.Url.GetLeftPart(UriPartial.Authority)? That should get the Scheme and Authority parts of the Url (which I believe are the protocol and domain you refer to). Here's the MSDN doc: http://msdn.microsoft.com/en-us/library/system.uri.getleftpart.aspx

like image 182
Ender Avatar answered Nov 15 '22 05:11

Ender