Click here to Skip to main content
15,867,704 members
Articles / Web Development / ASP.NET

ASP.NET ResolveUrl Without Page

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
2 Jun 2011CPOL 40.1K   9   2
Using ResolveUrl without Page

The Quick Answer

C#
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:

C#
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:

C#
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:

C#
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.

This article was originally posted at http://www.instanceofanobject.com/feeds/posts/default

License

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


Written By
Architect
Switzerland Switzerland
Senior IT Consultant working in Switzerland as Senior Software Engineer.

Find more at on my blog.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Prabhu Singh17-Feb-13 18:11
Prabhu Singh17-Feb-13 18:11 
I liked the way the solution was presented with appropriate context.
GeneralMy vote of 5 Pin
Alex B. Clarke16-Nov-12 0:42
Alex B. Clarke16-Nov-12 0:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.