[ASP.NET]將相對網址改為完整網址

剛好網友遇到這個問題,小喵寫了個小Function來提供轉換

緣起:

剛好網友遇到這個問題,小喵寫了個小Function來提供轉換

相對網址:

假設目前的路徑是http://www.dotblogs.com.tw/topcat,一般可能遇到的相對網址如以下的幾個

  • 在本來路徑下,子目錄下的另外一個檔案,例如:xxx/test.aspx→http://www.dotblogs.com.tw/topcat/xxx/test.aspx
  • 上層的相對路徑,例如:../xxx/test.aspx→http://www.dotblogs.com.tw/xxx/test.aspx
  • 本專案下的相對路徑,例如~/xxx/test.aspx→http://www.dotblogs.com.tw/topcat/xxx/test.aspx

轉換的Function:

Private Function ChgFullUrl(ByVal p As String) As String
    Dim s As String = ResolveUrl(p)
    Dim ServerName As String = Request.ServerVariables("SERVER_NAME")
    Return "http://" & ServerName & s
End Function

說明:

透過ResolveUrl將相對路徑轉換成真正的路徑,這部份一並解決上層路徑的【..】,相同專案內的【~】,與本來位置的相對子資料夾。

再補上【http://】,以及Server的網址名稱(Request.ServerVariables("SERVER_NAME")),就可以補全完整的路徑了。

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat