[英]How to get HttpWebRequest.AllowAutoRedirect to set the cookies when doing a GET/POST on the redrected page?
Is there a way to get the HttpWebRequest
object to take the set-cookie header into account when being automatically redirected to another page through the AllowAutoRedirect
feature? 有没有办法让
HttpWebRequest
对象在通过AllowAutoRedirect
功能自动重定向到另一个页面时考虑到set-cookie标头? I need it to maintain the cookie information across redirects; 我需要它来维护重定向的cookie信息; I'd rather not have to implement the redirect myself if the framework can do this for me.
如果框架可以为我做这个,我宁愿不必自己实现重定向。 This must be a common request since most login pages I've seen usually do this.
这必须是一个常见的请求,因为我见过的大多数登录页面通常会这样做。
I know to make separate requests (ie. different HttpRequest objects) work with cookies, you need to set the HttpRequest.CookieContainer property on both requests to the same instance of a CookieContainer . 我知道要使单独的请求(即不同的HttpRequest对象)使用cookie,您需要在对CookieContainer的同一实例的两个请求上设置HttpRequest.CookieContainer属性。 You might need that for this case as well.
对于这种情况,您可能也需要这样做。
If you don't want to use a CookieContainer, the following code will access a page, providing the cookie in the parameter. 如果您不想使用CookieContainer,以下代码将访问页面,在参数中提供cookie。 Then, it will download all cookies set by that page and return them as a List of strings.
然后,它将下载该页面设置的所有cookie并将其作为字符串列表返回。
Note that AllowAutoRedirect is set to false. 请注意,AllowAutoRedirect设置为false。 If you want to follow the redirect, pull that object out of the HttpWebResponse headers and then manually construct another web request.
如果要跟随重定向,请将该对象从HttpWebResponse标头中拉出,然后手动构建另一个Web请求。
Public Shared Function GetCookiesSetByPage(ByVal strUrl As String, ByVal cookieToProvide As String) As IEnumerable(Of String)
Dim req As System.Net.HttpWebRequest
Dim res As System.Net.HttpWebResponse
Dim sr As System.IO.StreamReader
'--notice that the instance is created using webrequest
'--this is what microsoft recomends
req = System.Net.WebRequest.Create(strUrl)
'set the standard header information
req.Accept = "*/*"
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)"
req.ContentType = "application/x-www-form-urlencoded"
req.AllowAutoRedirect = False
req.Headers.Add(HttpRequestHeader.Cookie, cookieToProvide)
res = req.GetResponse()
'read in the page
sr = New System.IO.StreamReader(res.GetResponseStream())
Dim strResponse As String = sr.ReadToEnd
'Get the cooking from teh response
Dim strCookie As String = res.Headers(System.Net.HttpResponseHeader.SetCookie)
Dim strRedirectLocation As String = res.Headers(System.Net.HttpResponseHeader.Location)
Dim result As New List(Of String)
If Not strCookie = Nothing Then
result.Add(strCookie)
End If
result.Add(strRedirectLocation)
Return result
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.