使用WebRequest.Create(URL)调用页面时无法检索会话值

时间:2018-07-07 08:45:21

标签: asp.net vb.net session

我有一个页面(email.aspx)正在检索会话值,并根据该值进行一些处理。

当我直接使用浏览器的URL从浏览器中调用email.ASPX时,一切运行正常,没有任何问题。

Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim emailaddress As String
        Dim x As String = ""
        x = Session("id")
        If x = "" Then
            emailaddress = "failed to get session"
        Else

            ' Do some staff here
        End If

        Response.Write(emailaddress)


    End Sub

但是当我尝试从另一个包含嵌入式vb.net代码的ASPX页面使用WebRequest.Create(URL)调用(email.aspx)时,我发现它无法检索导致错误的Session值!

Public Function getemailaddress() As String

        Dim sURL As String
        sURL = "http://sample/email.aspx"

        Dim wrGETURL As System.Net.WebRequest
        wrGETURL = System.Net.WebRequest.Create(sURL)


        Dim emailaddress As String
        Dim objStream As System.Net.HttpWebResponse
        objStream = wrGETURL.GetResponse

        If objStream.StatusCode = System.Net.HttpStatusCode.OK Then
            Dim responseStream As System.IO.StreamReader
            responseStream = New System.IO.StreamReader(objStream.GetResponseStream())
            emailaddress = responseStream.ReadToEnd()
        End If
        objStream.Close()


        Return emailaddress

    End Function

我不知道这个问题的原因

1 个答案:

答案 0 :(得分:0)

客户端的会话标识符存储在cookie中。 WebRequest仅在当前请求有效之前存储其cookie,然后将其删除。您需要创建一个“全局” CookieContainer并将其传递给您发出的Web请求,以便在不同请求之间共享Cookie。

取决于您在多个不同的位置发出请求,您可能希望将其作为参数传递给函数:

Public Function getemailaddress(ByVal Cookies As System.Net.CookieContainer) As String

    ...your code...

    'We need to cast wrGETURL to a HttpWebRequest.
    Dim wrGETURL As System.Net.HttpWebRequest
    wrGETURL = DirectCast(System.Net.WebRequest.Create(sURL), HttpWebRequest)

    'Set our cookie container.
    wrGETURL.CookieContainer = Cookies

    ...your code...

End Function

对于需要具有相同会话的每个请求,您需要使用相同的CookieContainer,因此在发出所有请求之前,请在代码中声明一个:

Dim Cookies As New System.Net.CookieContainer

MakeRequest1(Cookies) 'Example request.
MakeRequest2(Cookies) 'Example request.

'Make the email request, passing our cookie container to it.
Dim Email As String = getemailaddress(Cookies)