I wrote a simple unit test for Uri(baseUri, relativeUri)
constructor .NET 7.0
and found out that the relative part of the baseUri
is preserved only in one case, when:
baseUri
ends with slash '/'
relativeUri
to be added does not start with '/'
all cases below are successful
[Theory]
[InlineData("http://my.host.net", "some/path", "http://my.host.net/some/path")]
[InlineData("http://my.host.net/net", "/some/path", "http://my.host.net/some/path")]
[InlineData("http://my.host.net/net", "some/path", "http://my.host.net/some/path")]
[InlineData("http://my.host.net/net", "some/path/", "http://my.host.net/some/path/")]
[InlineData("http://my.host.net/net/", "/some/path", "http://my.host.net/some/path")]
[InlineData("http://my.host.net/net/", "some/path", "http://my.host.net/net/some/path")]
[InlineData("http://my.host.net/net/", "some/path/", "http://my.host.net/net/some/path/")]
public void CreateUriTest(string baseUrl, string path, string full)
{
var baseUri = new Uri(baseUrl);
var fullUri = new Uri(baseUri, path);
Assert.Equal(full, fullUri.ToString());
}
MSDN for .NET 7.0 explanation for Uri(Uri, String)
constructor is a bit unclear. It has 2 contradictory statements:
If the baseUri
has relative parts (like /api
), then the relative part must be terminated with a slash, (like /api/
), if the relative part of baseUri
is to be preserved in the constructed Uri.
Additionally, if the relativeUri
begins with a slash, then it will replace any relative part of the baseUri
The second statement always wins. In other words, starting '/' of the relativeUri
does replace the relative part of the baseUri
regardless of if it ends with a '/' or not.
/
in/controller
indicates "from root" where root ishttp://localhost:7777
. – Kaiserslauternnew Uri(baseUri, "./controller")
to state that your path is relative from the current path (denoted by the dot). This will returnhttp://localhost:7777/BasePath/controller
. – GowbaseUri
and yourrelativeUri
separate.Uri baseUri = new Uri("http://localhost:7777"); Uri uri = new Uri(baseUri, "/BasePath/controller");
That way there's nothing to accidentally overwrite. – Jhvh