views:

1506

answers:

2

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? I need it to maintain the cookie information across redirects; 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.

+2  A: 

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. You might need that for this case as well.

Jonathan
A: 

If you don't want to use a CookieContainer, the following code will access a page, providing the cookie in the parameter. Then, it will download all cookies set by that page and return them as a List of strings.

Note that AllowAutoRedirect is set to false. If you want to follow the redirect, pull that object out of the HttpWebResponse headers and then manually construct another web request.

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
Sean Turner