删除Request.Url的最后一段 [英] Remove last segment of Request.Url

查看:60
本文介绍了删除Request.Url的最后一段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

将更改为

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

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

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

推荐答案

使用 Uri 类可解析URI-您可以使用 Segments 属性访问所有段,并重建URI,而无需最后一个段.

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

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

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

这篇关于删除Request.Url的最后一段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆