Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET ResolveUrl Without Page

0.00/5 (No votes)
2 Jun 2011 1  
Using ResolveUrl without Page

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here