我正在尝试为跨域 AJAX POST 查询创建代理,为此,我需要将客户端(浏览器)请求中的 cookie 添加到我发送到 PHP 后端的 POST 请求中,这是使用 HttpWebRequest。为此,我将每个 Request.Cookie 添加到 HttpWebRequest.CookieContainer 对象中。出于某种原因,我添加到其中的任何 cookie 都没有到达我的 PHP 后端。
我从一些搜索中了解到 CookieContainer 对象是依赖于 URI 的(我什至不知道如何解释它!),所以也许这就是我的问题的原因。但是,我尝试将我的 cookie 上的域设置为不同的东西,它似乎并没有影响它。因此,URI 的含义可能与 Cookie 的域参数不同。如果是这样的话,我就卡住了。
如果存在替代解决方案,我完全赞成(如果有一种方法可以在不需要插件的情况下在 asp.net 中进行自动跨域代理,那将挽救我的生命!)。
这是我正在使用的代码。
<%@ Page Language="VB" validateRequest="false" Debug="true" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim displayValues As New StringBuilder()
Dim CookieJar as New CookieContainer
Dim objCookieColl as HttpCookieCollection
Dim objThisCookie As HttpCookie
Dim myCookie As HttpCookie
Dim arr1() As String
Dim myCount as Integer
objCookieColl = Request.Cookies
arr1 = objCookieColl.AllKeys
Dim postedValues As NameValueCollection = Request.Form
Dim nextKey As String
For i As Integer = 0 To postedValues.AllKeys.Length - 1
nextKey = postedValues.AllKeys(i)
If nextKey.Substring(0, 2) <> "__" Then
displayValues.Append("&" & nextKey)
displayValues.Append("=")
displayValues.Append(Server.UrlEncode(postedValues(i)))
End If
Next
Dim uri As New Uri("http://www.otherdomain.com/subfolder/backend.php")
Dim data As String = displayValues.ToString
If (uri.Scheme = uri.UriSchemeHttp) Then
Dim postRequest As HttpWebRequest = HttpWebRequest.Create(uri)
For index As Integer = 1 to UBound(arr1)
objThisCookie = objCookieColl(arr1(index))
Dim tempCookie As New Cookie(objThisCookie.Name, objThisCookie.Value, objThisCookie.Path, Request.ServerVariables("HTTP_HOST"))
myCount = myCount + 1
CookieJar.Add(tempCookie)
Next
postRequest.CookieContainer = CookieJar
postRequest.Method = Request.HttpMethod
postRequest.ContentLength = data.Length
postRequest.ContentType = "application/x-www-form-urlencoded"
Dim writer As New StreamWriter(postRequest.GetRequestStream())
writer.Write(data)
writer.Close()
Dim myResponse As HttpWebResponse = postRequest.GetResponse()
Dim x As Integer
While x < myResponse.Headers.Count
Response.AppendHeader(myResponse.Headers.Keys(x), myResponse.Headers(x))
x = x + 1
End While
Dim reader As New StreamReader(myResponse.GetResponseStream())
Dim responseString As String = reader.ReadToEnd()
myResponse.Close()
Response.Write(responseString)
End If
End If
End Sub
</script>