I’d like to extract the query string and fragment from a relative URI, that is, a URI without any scheme or host information.
Is there a more elegant way to do this than by turning it into an absolute URI with a fake host name?
var relativeUri = "/dir1/dir2/file?a=b&c=d#fragment";
var uri = new Uri(new Uri("http://example.com"), relativeUri);
var path = Uri.UnescapeDataString(String.Concat(uri.Segments));
var query = uri.Query;
var fragment = uri.Fragment;
// path = "/dir1/dir2/file", query = "?a=b&c=d", fragment = "#fragment"
Although you can create a
Uriwithout a host portion, most of its properties will then throw an InvalidOperationException (“This operation is not supported for a relative URI”) because those properties rely on an absolute Uri.HttpUtility.ParseQueryString()is indeed not going to help here, because it only operates on the query part of an Uri, which you cannot obtain because you don’t have an absolute Uri.So although it might seem hacky, I think the
new Uri(baseUri, relativeUri)contstructor does exactly what you want. I cannot seem to find a better or cleaner way to accomplish the same.