从 Uri.Segment.Last() 中删除结束斜线?
Removing end slash from Uri.Segment.Last()?
获取 System.Uri
的最后一段同时排除可选的结束斜杠的最安全方法是什么?例如,我有这些 URL:
http://example.com/test/12345
http://example.com/test/12345/
我只想从最后一段中获取“12345”,但是,调用 Segments.Last()
将 return 不同的字符串。在第一种情况下,我得到“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('/');
}
获取 System.Uri
的最后一段同时排除可选的结束斜杠的最安全方法是什么?例如,我有这些 URL:
http://example.com/test/12345
http://example.com/test/12345/
我只想从最后一段中获取“12345”,但是,调用 Segments.Last()
将 return 不同的字符串。在第一种情况下,我得到“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('/');
}