簡體   English   中英

確定2個URL是否相同的最安全的方法是什么?

[英]What's the safest way to determine if 2 URLs are the same?

如果我有URL A說http://www.example.com/和另一個,請說http://www.example.com 什么是最安全的方法來確定兩者是否相同,而不查詢網頁並進行差異?

例子:

  1. http://www.example.com/ VS http://www.example.com (上文提到)
  2. http://www.example.com/aa/../ VS http://www.example.com

編輯:澄清:只是想根據RFC 1738標准知道URL在等效的上下文中是否相同。

在.Net中,您可以使用System.Uri類。

讓u1 =新的Uri(“ http://www.google.com/ ”);;

val u1:Uri = http://www.google.com/

讓u2 =新的Uri(“ http://www.google.com ”);;

val u2:Uri = http://www.google.com/

u1.Equals(U2);;

val it:bool = true

要進行更細粒度的比較,可以使用Uri.Compare方法。 還有靜態方法來處理Uri字符串中各種形式的字符轉義和編碼,這無疑在徹底處理主題時非常有用。

沒有請求URL,你幾乎無能為力。 但您可以定義幾個啟發式方法:

  1. 刪除尾部斜杠
  2. 考慮.htm.html是一樣的
  3. 假設/base//base/ /base/index.html是相同的
  4. 刪除查詢字符串參數(可能,可能不是,取決於您的需要)
  5. 考慮url.comwww.url.com相同。

這完全取決於“相同”的URL究竟是什么意思。

為了讓那些不了解F#的人受益,這里有一個快速而骯臟但完整的C#控制台應用程序,它演示了如何使用Uri類來判斷兩個URL是否相同。 運行此代碼時,您應該看到兩行:“true”,后跟“false”:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(IsSameUrl("http://stackoverflow.com/", "http://stackoverflow.com").ToString());
            Console.WriteLine(IsSameUrl("http://stackoverflow.com/", "http://codinghorror.com").ToString());
            Console.ReadKey();
        }

        static bool IsSameUrl(string url1, string url2)
        {
            Uri u1 = new Uri(url1);
            Uri u2 = new Uri(url2);
            return u1.Equals(u2);
        }
    }
}

Yuval A答案中添加的內容很少:

  • www.google.com和http://www.google.com可能指向同一目標
  • www.google.com和google.com指向同一頁面(但通過重定向實現)
  • 可能會對Url進行編碼(請參閱HttpUtility.UrlEncode / Decode方法)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM