Pure way to trim QueryString from relative Uri C #

Given a URI like:

/path/page/?param1=value1&param2=value2

How would this be generated with:

Url.Action("page","path", new { param1 = "value", param2 = "value2" })

What would be the cleanest way to strip the query string so that it works out /path/page/?

After searching in SO specifically and for a wider Google search, the best answer I found was to create a Uri object and use uri.GetLeftPart(UriPartial.Path)that I already know and use for absolute URIs.

The problem is that this will not work for relative URIs, and both do

Uri uri = new Uri(new Uri("http://www.fakesite.com"), myRelativeUri)
string cleanUri = uri.AbsolutePath

and

string cleanUri = myRelativeUri.Substring(0, myRelativeUri.IndexOf('?'))

look messy.

+4
source share
3 answers

I would use string clearnUri = myRelativeUri.Split('?')[0];

It is about as clean as you are going.

+6
source

Substring, String.Remove, :

string cleanUri = myRelativeUri.Remove(myRelativeUri.IndexOf('?'));

, .

if (myRelativeUri.Contains('?'))
    cleanUri = myRelativeUri.Remove(myRelativeUri.IndexOf('?'));
+2

There is nothing in the .NET Framework to help you with this ...

I would vote for string manipulations if you prefer inline code - the trick with creating an absolute Uri does not work for less relative URLs of a schema, for example "//sample.com/file?query".

0
source

All Articles