Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse relative URI

Tags:

.net

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"
like image 642
Tim Robinson Avatar asked Nov 26 '12 12:11

Tim Robinson


2 Answers

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.

like image 126
CodeCaster Avatar answered Nov 07 '22 04:11

CodeCaster


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())
like image 4
workabyte Avatar answered Nov 07 '22 02:11

workabyte