Tim Robinson
Tim Robinson

Reputation: 54724

Parse relative URI

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"

Upvotes: 33

Views: 12223

Answers (2)

workabyte
workabyte

Reputation: 3755

Running into this issue myself i found that HttpUtility.ParseQueryString is really only looking for a string and anything after the '?'

so being that i have to use this in both cases (relative and absolute) I find the following seems to work quite well

HttpUtility.ParseQueryString(url.Split('?').Last())

Upvotes: 6

CodeCaster
CodeCaster

Reputation: 151588

Although you can create a Uri without 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.

Upvotes: 24

Related Questions