Getting the absolute URL of the page in code

I am new to ASP.NET and trying to convert a web application from using hard-coding locations (i.e. / base / path / index.aspx) to detect them at runtime. If I use Response.Redirect() , I can express the path as '~ / index.aspx', and at runtime, ASP.NET will build the correct URL for sending the redirect based on where the web application is being deployed.

There are places in the code where Javascript and / or HTML are dynamically generated and sent to the client as part of the response to force a new window. In these cases, I do not know how to get the actual URL that should be opened in a new window. Using ~ does not work in this case, as the URL is evaluated by the browser, not the server. Is there a class or method in ASP.NET that will give me the url I'm looking for? I would have looked for myself, but I don’t even know how to tell about my question correctly.

+4
source share
4 answers

The VirtualPathUtility class is what you are looking for

http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility.aspx

In particular, you can use these methods:

 VirtualPathUtility.ToAbsolute("~/"); VirtualPathUtility.ToAppRelative("~/"); 
+7
source

You can do something like this:

 <head runat="server"> <title>Untitled Page</title> <script type="text/javascript"> var url = '<%= ResolveUrl("~/path/some_page.aspx") %>'; window.open(url, 'name'); </script> </head> <body> <form id="form1" runat="server"></form> </body> </html> 
+2
source

Tilde (~) is basically a shortcut to HttpRuntime.AppDomainAppVirtualPath .

+1
source

You can use Request.ApplicationPath and create your page path.

0
source

All Articles