I would like to remove the last segment of Request.Url
, so for instance...
http://www.example.com/admin/users.aspx/deleteUser
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;
}