17

我想删除 的最后一段Request.Url,例如...

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

会变成

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

我更喜欢 linq,但接受任何有效的解决方案。

4

5 回答 5

18

使用Uri该类来解析 URI - 您可以使用该Segments属性访问所有段并在没有最后一个段的情况下重建 URI。

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 `/`

作为获取方案和主机名的替代方法,正如 Dour High Arch 在他的评论中所建议的那样:

var noLastSegment = uri.GetComponents(UriComponents.SchemeAndServer, 
                                      UriFormat.SafeUnescaped);
于 2012-07-17T19:19:51.180 回答
14

与@Oded 的答案大致相同,但使用 UriBuilder 代替:

var uri = new Uri("http://www.example.com/admin/users.aspx/deleteUser");
var newSegments = uri.Segments.Take(uri.Segments.Length - 1).ToArray();
newSegments[newSegments.Length-1] = 
    newSegments[newSegments.Length-1].TrimEnd('/');
var ub=new UriBuilder(uri);
ub.Path=string.Concat(newSegments);
//ub.Query=string.Empty;  //maybe?
var newUri=ub.Uri;
于 2012-07-17T19:36:19.010 回答
9

要删除 Request.Url 的最后一段,从绝对 uri 中减去最后一段的长度就足够了。

string uriWithoutLastSegment = Request.Url.AbsoluteUri.Remove(
  Request.Url.AbsoluteUri.Length - Request.Url.Segments.Last().Length );
于 2015-07-15T08:31:45.673 回答
1

我发现操纵 Uri 相当烦人,并且由于其他答案非常冗长,这是我的两分钱以扩展方法的形式。

作为奖励,您还可以获得替换最后分段方法。这两种方法都会使查询字符串和 url 的其他部分保持不变。

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;
}
于 2019-03-06T08:26:02.323 回答
0

那么简单的解决方案是从字符串的末尾到字符串的开头逐个字符地迭代,并搜索第一个'/'来(我想这也进入了你的脑海)。

试试这个:

string url = "http://www.example.com/admin/users.aspx/deleteUser";

for (int i = url.Length - 1; i >= 0; i--) {

    if (url[i] == '/') return url.Substring(0, i - 1);
}
于 2012-07-17T19:25:43.193 回答