Remove last segment of Request.Url

Viewed 30454

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.

5 Answers

I find manipulating Uri's fairly annoying, and as the other answers are quite verbose, here's my two cents in the form of an extension method.

As a bonus you also get a replace last segement method. Both methods will leave querystring and other parts of the url intact.

public static class UriExtensions
{
    private static readonly Regex LastSegmentPattern = 
        new Regex(@"([^:]+://[^?]+)(/[^/?#]+)(.*$)", RegexOptions.Compiled | RegexOptions.IgnoreCase);        

    public static Uri ReplaceLastSegement(this Uri me, string replacement)
        => me != null ? new Uri(LastSegmentPattern.Replace(me.AbsoluteUri, $"$1/{replacement}$3")) : null;

    public static Uri RemoveLastSegement(this Uri me)
        => me != null ? new Uri(LastSegmentPattern.Replace(me.AbsoluteUri, "$1$3")) : null;
}
Related