Remove last segment of Request.Url

前端 未结 5 623
旧巷少年郎
旧巷少年郎 2021-01-07 22:59

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

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

5条回答
  •  隐瞒了意图╮
    2021-01-07 23:58

    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;
    }
    

提交回复
热议问题