Click here to Skip to main content
Licence CPOL
First Posted 2 Jun 2011
Views 9,418
Bookmarked 8 times

ASP.NET ResolveUrl Without Page

By | 2 Jun 2011 | Technical Blog
Using ResolveUrl without Page.
A Technical Blog article. View original blog here.[^]

The quick answer

System.Web.VirtualPathUtility.ToAbsolute("~/default.aspx");

Don't forget the ~/ (tilde) before the page name.

The lengthy explanation

Assume that we want to redirect to default.aspx that's on the site root:

Response.Redirect("default.aspx");

If we're on a page that's also on the root, it will map to http://www.mysite.com/default.aspx and work correctly.

The problem

The problem comes when we're not on the site root but inside a child folder. Let's say we're on a page that's inside the /Administration folder, the same line will map to http://www.mysite.com/Administration/default.aspx and that of course won't resolve and return a glorious 404: Page Not Found.

The solution

Solving this is easy using the ResolveUrl method:

Response.Redirect(ResolveUrl("~/default.aspx"));

Where this won't work

ResolveUrl is only available within the context of a Page or a UserControl; if you're, for instance, inside an ASHX, this method isn't available. In these cases, you have to use the following line to do the job:

System.Web.VirtualPathUtility.ToAbsolute("~/default.aspx");

We must include the tilde before the page name to make it a relative path, otherwise this method will throw an exception.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

AlexCode

Architect
AlexCode
Portugal Portugal

Member

Alexandre Simões is a freelancer working as senior software architect with the focus on Financial Web Applications.
 
Find more about me on my blog.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 2 Jun 2011
Article Copyright 2011 by AlexCode
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid