Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last segment of Request.Url

Tags:

c#

I would like to remove the last segment of Request.Url, so for instance...

http://www.example.com/admin/users.aspx/deleteUser

would change to

http://www.example.com/admin/users.aspx

I would prefer linq but accept any solution that efficiently works.

like image 461
bflemi3 Avatar asked Jul 17 '12 19:07

bflemi3


1 Answers

Use the Uri class to parse the URI - you can access all the segments using the Segments property and rebuild the URI without the last segment.

var uri = new Uri(myString);

var noLastSegment = string.Format("{0}://{1}", uri.Scheme, uri.Authority);

for(int i = 0; i < uri.Segments.Length - 1; i++)
{
   noLastSegment += uri.Segments[i];
}

noLastSegment = noLastSegment.Trim("/".ToCharArray()); // remove trailing `/`

As an alternative to getting the scheme and host name, as suggested by Dour High Arch in his comment:

var noLastSegment = uri.GetComponents(UriComponents.SchemeAndServer, 
                                      UriFormat.SafeUnescaped);
like image 183
Oded Avatar answered Oct 03 '22 22:10

Oded