在
ASP.Net
中,可以通过 URL 从几乎相同的页面获取相同的内容,例如
localhost:9000/Index.aspx
和 localhost:9000//Index.aspx
甚至 localhost:9000///Index.aspx
但这对我来说看起来不太好。
在用户转到某个页面之前以及在什么位置之前,如何删除这些额外的斜杠?
使用这个:
url = Regex.Replace(url , @"/+", @"/");
它将支持n次
见
https://stackoverflow.com/a/19689870
https://msdn.microsoft.com/en-us/library/9hst1w91.aspx#Examples
您需要指定一个基本 Uri 和一个相对路径来获取规范化的行为。
Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
Console.WriteLine(myUri.ToString());
这个解决方案不是那么漂亮,但很简单
do
{
url = url.Replace("//", "/");
}
while(url.Contains("//"));
这适用于网址中的许多斜杠,但运行时间不是那么好。
删除它们,例如:
url = url.Replace("///", "/").Replace("//", "/");
Regex.Replace("http://localhost:3000///////asdasd/as///asdasda///asdasdasd//", @"/+", @"/").Replace(":/", "://")
以下是组合 URL 段的代码片段,能够删除重复的斜杠:
public class PathUtils
{
public static string UrlCombine(params string[] components)
{
var isUnixPath = Path.DirectorySeparatorChar == '/';
for (var i = 1; i < components.Length; i++)
{
if (Path.IsPathRooted(components[i])) components[i] = components[i].TrimStart('/', '\\');
}
var url = Path.Combine(components);
if (!isUnixPath)
{
url = url.Replace(Path.DirectorySeparatorChar, '/');
}
return Regex.Replace(url, @"(?<!(http:|https:))//", @"/");
}
}
我在 PowershellCore 中使用它
$Uri -replace "(?<!:)/{2,}", "/"