>我有一个页面(电子邮件.aspx(正在检索会话值,并根据该值进行一些处理。
当我打电话给电子邮件时。ASPX直接从浏览器使用其URL一切正常,没有任何问题。
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(调用(电子邮件.aspx(时,我发现它无法检索会话值,从而导致错误!
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
我无法弄清楚这个问题背后的原因
客户端的会话标识符存储在 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)