asp如何获取当前访问页面的完整地址?
|
admin
2025年12月11日 9:19
本文热度 6
|
在ASP中,获取当前页面的完整地址(包括协议、域名、路径和查询参数)可以通过组合服务器变量来实现。以下是实现代码:
<%
Function GetFullUrl()
Dim protocol, serverName, serverPort, scriptName, queryString, fullUrl
' 获取协议(HTTP/HTTPS)
If Request.ServerVariables("HTTPS") = "on" Then
protocol = "https://"
Else
protocol = "http://"
End If
' 获取服务器域名
serverName = Request.ServerVariables("SERVER_NAME")
' 获取端口(非标准端口时显示)
serverPort = Request.ServerVariables("SERVER_PORT")
If (serverPort = "80" And protocol = "http://") Or (serverPort = "443" And protocol = "https://") Then
serverPort = ""
Else
serverPort = ":" & serverPort
End If
' 获取当前页面路径
scriptName = Request.ServerVariables("SCRIPT_NAME")
' 获取查询字符串(如果有)
queryString = Request.ServerVariables("QUERY_STRING")
If queryString <> "" Then
queryString = "?" & queryString
End If
' 组合完整URL
fullUrl = protocol & serverName & serverPort & scriptName & queryString
GetFullUrl = fullUrl
End Function
' 使用示例
Response.Write "当前完整地址: " & GetFullUrl()
%>
关键点说明:
- 协议判断:通过
HTTPS 服务器变量判断是否使用 HTTPS - 域名获取:
SERVER_NAME 获取服务器域名或IP - 端口处理:
- 默认端口(HTTP 80 / HTTPS 443)自动隐藏
- 非标准端口会显示(如
:8080)
- 路径获取:
SCRIPT_NAME 获取当前页面虚拟路径 - 查询参数:
QUERY_STRING 获取问号后的参数部分
输出示例:
当前完整地址: https://www.example.com:8080/products/index.asp?id=123
注意事项:
- 在负载均衡环境中,
SERVER_NAME 可能返回内部服务器名,需根据实际情况调整 - 如需包含锚点(#hash),客户端需使用 JavaScript(ASP 是服务器端技术)
- 特殊字符已自动处理(URL 编码由浏览器负责)
通过这个方法,您可以准确获取用户浏览器地址栏中显示的完整 URL。
该文章在 2025/12/11 9:19:43 编辑过