从ASP.NET页面获取请求变量

And*_*ers 7 vb.net asp.net parameters request

我写了以下函数,大约95%的时间都有效,但我需要它100%工作(显然):

Public Shared Function getPassedVars() As String   
    Const keyCount As Integer = 54 ' 54 seems to be the number of parameter keys passed by default (for this web_app).
    '                                there are more if there is a form involved (ie. from search page)

    Dim oParams As String = ""
    Try
        With HttpContext.Current
            If .Request.Params.AllKeys.Count > keyCount Then
                For i As Integer = 0 To (.Request.Params.AllKeys.Count - (keyCount + 1))
                    oParams &= String.Format("{0}={1}{2}", .Request.Params.Keys.Item(i), .Request.Params(i), IIf(i < .Request.Params.AllKeys.Count - (keyCount + 1), ";", ""))
                Next
            End If
        End With
        Return oParams
    Catch ex As Exception
        Return Nothing
    End Try
End Function
Run Code Online (Sandbox Code Playgroud)

它擦除了Request.Params传递变量的对象,这些变量位于数组的开头(其余的是ASP参数).我很确定我已经看到了获得这些参数的不同方法,但我无法弄明白.有什么建议?

编辑

所以看起来我可以使用它Request.URL.Query来实现这一点,我会调查这个并发回.

这是我想出的:

Public Shared Function getPassedVars() As String
    Dim oParams As String = ""
    Dim qString As String = ""
    Dim oSplit As New List(Of String)
    Try
        With HttpContext.Current
            qString = .Request.Url.Query
            If qString.Length > 0 Then 'do we have any passed variables?
                If qString.StartsWith("?") Then qString = qString.Remove(0, 1) 'remove leading ? from querystring if it is there
                oSplit.AddRange(qString.Split("&"))
                For i As Integer = 0 To oSplit.Count - 1
                    oParams &= String.Format("{0}{1}", oSplit.Item(i), IIf(i < oSplit.Count - 1, ";", ""))
                Next
                Return oParams
            Else
                 Return Nothing
            End If
        End With
    Catch ex As Exception
        Return Nothing
    End Try
End Function
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.

Not*_*tMe 9

Request.QueryString是一个NameValueCollection,因此获取"参数"的最简单方法是执行以下操作:

    foreach (String s in Request.QueryString) {
        Response.Write(s + " = " + Request.QueryString[s]);
    }
Run Code Online (Sandbox Code Playgroud)

你的职能在哪里?如果它在页面的代码中执行,那么你肯定不需要使用HttpContext变量.


Ada*_*lph 8

看起来您正在尝试从查询字符串中获取值.

例如,对于此URL: -

http://www.tempuri.org/mypage.aspx?param1=x&param2=y
Run Code Online (Sandbox Code Playgroud)

我假设你想要检索查询字符串参数param1和param2的值?

如果是这样,只需使用: -

Dim param1 as String = Request.QueryString("param1")
Run Code Online (Sandbox Code Playgroud)

否则,如果这些参数包含在表单中(HTTP POST请求),则使用Mitchel Sellers建议的方法.


Mit*_*ers 1

如果您知道名称,则可以使用以下命令通过键值获取它

Dim myParamValue as String = Request.Form("MyKeyName")
Run Code Online (Sandbox Code Playgroud)

否则,您可以通过键等循环遍历表单集合以获取值。关键是,你真的需要解析所有 54 个项目吗?或者您只是在寻找一些特定的值?