萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 取得完整 URL 含查詢字串:ServerVariables 與 QueryString 綜合應用

ASP 完整 URL 重建:含協定、主機、連接埠、路徑與查詢字串

在分享、重導向、記錄日誌、OAuth 回調等場景,需要重建完整的請求 URL。本文提供健全的 GetFullUrl() 函數,處理 HTTP/HTTPS、非標準連接埠、URL 編碼、多值查詢參數等邊界情況。

核心函數:GetFullUrl

<%
Function GetFullUrl(includeQuery)
    Dim protocol, host, port, path, query, fullUrl
    Dim serverPort, isSecure
    
    ' 協定判斷
    isSecure = (LCase(Request.ServerVariables("HTTPS")) = "on")
    If isSecure Then
        protocol = "https://"
    Else
        protocol = "https://"
    End If
    
    ' 主機名
    host = Request.ServerVariables("HTTP_HOST")
    If host = "" Then host = Request.ServerVariables("SERVER_NAME")
    
    ' 連接埠處理(標準港不顯示)
    serverPort = Request.ServerVariables("SERVER_PORT")
    If (isSecure And serverPort <> "443") Or (Not isSecure And serverPort <> "80") Then
        host = host & ":" & serverPort
    End If
    
    ' 路徑
    path = Request.ServerVariables("URL")  ' 或 SCRIPT_NAME
    If path = "" Then path = "/"
    
    ' 查詢字串
    query = ""
    If includeQuery = True Or includeQuery = 1 Then
        Dim qs, key, val, encodedVal
        qs = Request.QueryString
        If qs.Count > 0 Then
            query = "?"
            For Each key In qs
                ' 處理多值參數:Request.QueryString(key) 回傳逗號分隔字串
                ' 需逐個值編碼
                val = qs(key)
                ' 簡易處理:直接編碼整個值(含逗號)
                encodedVal = Server.URLEncode(val)
                query = query & key & "=" & encodedVal & "&"
            Next
            ' 移除尾端 &
            If Right(query, 1) = "&" Then query = Left(query, Len(query) - 1)
        End If
    End If
    
    fullUrl = protocol & host & path & query
    GetFullUrl = fullUrl
End Function

' 使用
Response.Write "完整 URL:" & GetFullUrl(True) & "
" Response.Write "無查詢字串:" & GetFullUrl(False) & "
" %>

進階版:支援多值參數正確編碼

<%
Function GetFullUrlAdvanced(includeQuery)
    Dim protocol, host, port, path, query, fullUrl
    Dim serverPort, isSecure, qs, key, vals, val, i, encodedVal
    
    isSecure = (LCase(Request.ServerVariables("HTTPS")) = "on")
    protocol = IIf(isSecure, "https://", "https://")
    
    host = Request.ServerVariables("HTTP_HOST")
    If host = "" Then host = Request.ServerVariables("SERVER_NAME")
    
    serverPort = Request.ServerVariables("SERVER_PORT")
    If (isSecure And serverPort <> "443") Or (Not isSecure And serverPort <> "80") Then
        host = host & ":" & serverPort
    End If
    
    path = Request.ServerVariables("URL")
    If path = "" Then path = "/"
    
    query = ""
    If includeQuery Then
        qs = Request.QueryString
        If qs.Count > 0 Then
            query = "?"
            For Each key In qs
                ' 正確處理多值:Request.QueryString(key) 可能回傳 "val1,val2"
                ' 需用 Request.QueryString(key)(index) 逐個取值
                ' 但 ASP 經典 QueryString 集合不直接支援索引存取多值
                ' 替代:解析原始 QUERY_STRING
            Next
        End If
    End If
    
    ' 更可靠:解析 RAW QUERY_STRING
    Dim rawQuery, pairs, pair, eqPos, k, v
    rawQuery = Request.ServerVariables("QUERY_STRING")
    If includeQuery And rawQuery <> "" Then
        query = "?"
        pairs = Split(rawQuery, "&")
        For i = 0 To UBound(pairs)
            pair = pairs(i)
            eqPos = InStr(pair, "=")
            If eqPos > 0 Then
                k = Left(pair, eqPos - 1)
                v = Mid(pair, eqPos + 1)
                ' 解碼再編碼,確保格式標準
                query = query & Server.URLEncode(Server.URLDecode(k)) & "=" & Server.URLEncode(Server.URLDecode(v)) & "&"
            Else
                query = query & Server.URLEncode(pair) & "=&"
            End If
        Next
        If Right(query, 1) = "&" Then query = Left(query, Len(query) - 1)
    End If
    
    fullUrl = protocol & host & path & query
    GetFullUrlAdvanced = fullUrl
End Function

Function IIf(cond, t, f)
    If cond Then IIf = t Else IIf = f
End Function
%>

實際應用場景

1. 分享連結生成

<%
' 產生分享連結(含追蹤參數)
Dim shareUrl, baseUrl
baseUrl = GetFullUrl(False)  ' 不含原查詢字串
shareUrl = baseUrl & "?utm_source=share&utm_medium=web&utm_campaign=article_" & Request.QueryString("id")
Response.Write "分享本文"
%>

2. OAuth 回調 URL

<%
' 建構 OAuth redirect_uri(需精確匹配註冊的 URI)
Dim redirectUri
redirectUri = GetFullUrl(False) & "?action=oauth_callback&provider=google"
' 註冊時需包含完整路徑與查詢參數結構
%>

3. 記錄完整請求 URL 供審計

<%
Sub LogRequest()
    Dim logSql, fullUrl
    fullUrl = GetFullUrlAdvanced(True)
    logSql = "INSERT INTO AccessLog (FullUrl, IP, UserAgent, Referer, Time) VALUES (?, ?, ?, ?, Now())"
    ExecuteNonQuery logSql, Array(fullUrl, GetRealIP(), Request.ServerVariables("HTTP_USER_AGENT"), Request.ServerVariables("HTTP_REFERER"))
End Sub
%>

4. 重導向保持查詢參數

<%
' 登入後導回原頁
Dim returnUrl
returnUrl = Request.QueryString("return_url")
If returnUrl = "" Then
    returnUrl = GetFullUrlAdvanced(True)
End If

' 登入處理後
If loginSuccess Then
    Response.Redirect returnUrl
End If
%>

URL 編碼最佳實務

  • 路徑段落:Server.URLEncode(空格→+,保留 /)
  • 查詢參數值:Server.URLEncode(空格→+)
  • 查詢參數名:通常不需編碼,但為保險亦編碼
  • 完整 URL:不要對整個 URL 編碼,只編碼組成部分
  • 雙重編碼風險:避免對已編碼字串再次編碼

反向解析:從完整 URL 提取元件

<%
Function ParseUrl(fullUrl)
    Dim result, protocolEnd, authStart, authEnd, pathStart, queryStart, fragmentStart
    Set result = Server.CreateObject("Scripting.Dictionary")
    
    ' 協定
    protocolEnd = InStr(fullUrl, "://")
    If protocolEnd > 0 Then
        result("protocol") = Left(fullUrl, protocolEnd - 1)
        authStart = protocolEnd + 3
    Else
        authStart = 1
    End If
    
    ' 授權區段 (user:pass@host:port)
    authEnd = InStr(authStart, fullUrl, "/")
    queryStart = InStr(authStart, fullUrl, "?")
    fragmentStart = InStr(authStart, fullUrl, "#")
    
    Dim pathEnd
    pathEnd = Len(fullUrl) + 1
    If queryStart > 0 And queryStart < pathEnd Then pathEnd = queryStart
    If fragmentStart > 0 And fragmentStart < pathEnd Then pathEnd = fragmentStart
    If authEnd > 0 And authEnd < pathEnd Then pathEnd = authEnd
    
    If authEnd > 0 And authEnd < pathEnd Then
        result("authority") = Mid(fullUrl, authStart, authEnd - authStart)
        result("path") = Mid(fullUrl, authEnd, pathEnd - authEnd)
    Else
        result("authority") = Mid(fullUrl, authStart, pathEnd - authStart)
        result("path") = "/"
    End If
    
    If queryStart > 0 Then
        result("query") = Mid(fullUrl, queryStart + 1, (IIf(fragmentStart > 0, fragmentStart, Len(fullUrl) + 1) - queryStart - 1))
    End If
    
    If fragmentStart > 0 Then
        result("fragment") = Mid(fullUrl, fragmentStart + 1)
    End If
    
    ' 解析 authority 中的 host:port
    Dim atPos, colonPos, auth
    auth = result("authority")
    atPos = InStrRev(auth, "@")
    If atPos > 0 Then
        result("userinfo") = Left(auth, atPos - 1)
        auth = Mid(auth, atPos + 1)
    End If
    colonPos = InStrRev(auth, ":")
    If colonPos > 0 And InStr(colonPos, auth, "/") = 0 Then  ' 排除 IPv6
        result("host") = Left(auth, colonPos - 1)
        result("port") = Mid(auth, colonPos + 1)
    Else
        result("host") = auth
        result("port") = IIf(result("protocol") = "https", "443", "80")
    End If
    
    Set ParseUrl = result
End Function
%>
copyright © 萬盛學電腦網 all rights reserved