Part of the path is overwritten when two URIs merge

I need to combine two URLs that contain .Path information.

I would like to use Uri.TryCreate () to enable me, so I can catch the wrong URLs.

The problem I am facing is that the base URI of the path is ignored when I combine the absolute and relative URIs:

Uri absoluteUri= new Uri("http://hostname/path/", UriKind.Absolute);
Uri relativeUri = new Uri("/my subsite/my page.aspx?my=query", UriKind.Relative);
Uri resultUri;
if (!Uri.TryCreate(absoluteUri, relativeUri, out resultUri))
      // handle errors

The conclusion above:

http://hostname/my%20subsite/my%20page.aspx?my=query

I would like to:

http://hostname/path/my%20subsite/my%20page.aspx?my=query

Is there a way to combine URLs that contain path information using a class Uri?

+5
source share
1 answer

Your relative URI should be relative, i.e. Delete the first slash (or add a period)

string relative = "/my subsite/my page.aspx?my=query";

Uri test1= new Uri(relative.Substring(1), UriKind.Relative); // without 'root'
Uri test2= new Uri("." + relative, UriKind.Relative);        // with 'current'

:

Uri baseUri = new Uri("http://hostname/path/");
string relative = "/my subsite/my page.aspx?my=query";

Uri test1 = new Uri(baseUri, relative);              // original string
Uri test2 = new Uri(baseUri, relative.Substring(1)); // without 'root' character
Uri test3 = new Uri(baseUri, "." + relative);        // with 'current' character

Console.WriteLine(test1.OriginalString); // wrong
Console.WriteLine(test2.OriginalString); // right!
Console.WriteLine(test3.OriginalString); // right!

, , , :

if (relative.StartsWith("/"))
    relative = "." + relative;
+12

All Articles