获得System.Uri
最后一段的最安全方法是什么,同时排除可选的结束斜线?例如,我有这些网址:
http://example.com/test/12345
http://example.com/test/12345/
我希望从最后一段获得“12345”,但是,调用Segments.Last()
会返回不同的字符串。在第一种情况下,我得到“12345”,但在第二种情况下,我得到“12345 /”。
这就是我所拥有的,但似乎并不是很干净,我担心我不会考虑一些奇怪的边缘情况而违反URI规范:
public static string Test(Uri link)
{
return link.Segments.Last().Replace("/", "");
}
编辑:绝对荒谬的是这被标记为关闭
你可以简单地使用TrimEnd()
:
public static string Test(Uri link)
{
return link.Segments.Last().TrimEnd('/');
}