Uri.MakeRelativeUri Behavior On Mono

2019-07-03 22:32发布

问题:

I'm seeing some strange (to me anyway) behavior when using MakeRelativeUri on Mono (2.6.7). Take the following example:

var uri1 = new Uri("/somepath/someothersubpath/");
var uri2 = new Uri("/somepath/img/someimg.jpg");

var uri3 = uri1.MakeRelativeUri(uri2);
Console.WriteLine(uri3.OriginalString);

I'd expect this to output "../img/someimg.jpg", but I get "img/someimg.jpg"

A friend has confirmed using windows/visual studio that he gets my expected result if appending an extra slash to the beginning of the string (I've tried this as well, and to no avail).

I'm not sure if this is an issue with the Uri class in mono, or if my understanding of how the URI class should work is flawed, but any advice that can help me get to the expected output would be greatly appreciated.

Thanks,

Alex

回答1:

It seems like it's making it relevant to someothersubpath itself, not to its children.

I'm not sure about it, but maybe it's possible to get around this by appending anything to the first string:

var uri1 = new Uri("/somepath/someothersubpath/anything");
var uri2 = new Uri("/somepath/img/someimg.jpg");

var uri3 = uri1.MakeRelativeUri(uri2);
Console.WriteLine(uri3.OriginalString);


回答2:

The Microsoft .NET documentation for Uri.MakeRelativeUri says that it should throw InvalidOperationException for relative Uris.

Your code, as written, throws an exception on the first line: "Invalid URI: The format of the URI could not be determined." If I modify the code:

    var uri1 = new Uri("/somepath/someothersubpath/", UriKind.RelativeOrAbsolute);
    var uri2 = new Uri("/somepath/img/someimg.jpg", UriKind.RelativeOrAbsolute);

    var uri3 = uri1.MakeRelativeUri(uri2);

Then the last line throws InvalidOperationException: This operation is not supported for a relative URI. Just as the documentation says it should.

So it appears that the Mono implementation is at odds with the .NET documentation.



标签: c# mono uri