Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to truncate QueryString from a relative Uri c#

Tags:

c#

asp.net

Given a URI like:

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

As it would be generated by using:

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

What would be the cleanest way to strip the query string so it would result in /path/page/?

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

Problem is, this will not work for relative URIs, and both doing

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

and

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

look sloppy.

like image 774
Miguel Avatar asked Jan 08 '23 11:01

Miguel


1 Answers

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

It's about as clean as you're going to get.

like image 186
David Francis Avatar answered Jan 17 '23 16:01

David Francis