Wednesday, November 17, 2010

Get a Fully Qualified URL from a Virtual Path

I needed to create a page to handle 404 errors ("Page Not Found"), and automatically redirect them to a related page within the web site. I ran into a little problem when I tried to display the fully qualified URL from a virtual path (all done on the server side in C#). 

With some input from an associate (who suggested I use Url.GetLeftPart), I came up with the following solution:

string fullyQualifiedUrl = GetFullyQualifiedUrl("~/Home");

private string GetFullyQualifiedUrl(string virtualPath)
{
    HttpRequest request = HttpContext.Current.Request;
    string urlLeftPart = request.Url.GetLeftPart(UriPartial.Authority);
    string appPath = request.ApplicationPath;
    string fullyQualifiedUrl = string.Format("{0}{1}{2}", urlLeftPart, appPath, virtualPath).Replace("~/", "");
    return fullyQualifiedUrl;
}


Share & Enjoy!

No comments:

Post a Comment