我有这个URL:http://localhost:49500/Learning/Chapitre.aspx?id=2
如何仅获取此URL中
id
的值?id
的值?Request.QueryString()
数组访问所有查询字符串:
Request.QueryString("id")
将给您返回 2
。Request.QueryString["id"]
,注意方括号。 - WTFZane尽管我自己的评论说已经回答了,这里是代码。
Dim idval As String = System.Web.HttpUtility.ParseQueryString("http://localhost:49500/Learning/Chapitre.aspx?id=2")("id")
你可以使用 Request vb 方法,使用以下网址: http://localhost:49500/Learning/Chapitre.aspx?id=2
Dim valueId = Request("id")
测试代码:
response.Write(valueId)
值 Id 为 2
使用URL创建System.Uri
类的新实例,然后使用Query
属性获取查询字符串部分。
一旦获得该字符串,对'&'字符进行String.Split
。对于结果数组中的每个字符串,在'='字符上进行String.Split
。在结果数组中,第一个字符串是查询参数名称,第二个是值(如果存在)。检查名称是否是您感兴趣的名称,如果是,则获取该值。
更新:天哪,我自1999年以来就没有碰过VB了... :-)
这是我的答案代码。我没有意识到要解析的URL是页面URL。对于这种特定情况,Request.QueryString("id")
确实是更好的解决方案。
Dim url As Uri = New Uri("http://localhost:49500/Learning/Chapitre.aspx?id=2")
Dim query As String = url.Query.Trim("?")
Dim parameters() As String = query.Split("&")
Dim tokens() As String
Dim value As String = ""
For index As Integer = 0 To parameters.Length - 1
tokens = parameters(index).Split("=")
If tokens(0).ToLower = "id" Then
If tokens.Length = 2 Then
value = tokens(1)
End If
Exit For
End If
Next
' At this point value contains the parameter value or
' is empty if the parameter has no value or if the parameter is not present