Search code examples
c#asp.net.neturi

How does Response.Redirect calculate the URL for "~/folder1/folder2/some.aspx"


This might sound like a trivial problem but for some reason it is not.

Instead of needing to redirect

Response.Redirect("~/folder1/folder2/some.aspx")

I need the location as if it behaved like

string navigatingUrl = Response.Redirect("~/folder1/folder2/some.aspx")

Trying to replicate this I started with

string navigatingUrl = new Uri(HttpContext.Current.Request.Url,
                     new Uri("~/folder1/folder2/some.aspx", UriKind.Relative));

This instead generates "http://www.fullRequestUrl/~/folder1/folder2/some.aspx"

Edit: Well I've found out why I absolutely hate the URL API from Microsoft. I wish hellfire to whoever wrote this line of code

else if (uriKind == UriKind.Relative) 
{
// Here we know that we can create an absolute Uri, but the user has requested 
    only a relative one
e = GetException(ParsingError.CannotCreateRelative);
} 

What would possess someone to throw an error like that? This single if statement completely destroys the API.


Solution

  • Stealing from Get absolute url for a file in my asp.net project to include HTTP// etc for use externally? the only absolute way to do this is:

    string url = Request.Url.GetLeftPart(UriPartial.Authority) 
                        + VirtualPathUtility.ToAbsolute(relativePath)