Problem programmatically downloading file from forms authenticated site
-
I have a windows forms application where I need to download or get access to a response stream for a requested URL (In my case a gif file). The website uses forms authentication and therefore requires an authentication cookie and no resources on the site can be downloaded without first being redirected to a login page. I found this article Screen Scraping, ViewState, and Authentication using ASP.Net[^] from which I converted C# to VB.NET (the main difference is that the example code is run from an asp.NET application). However when I try to run my code I get a WebException (500) Internal Server Error. Here is my code, does anyone have any suggestions or hints/another way of doing this?
Dim strPageURL As String = "http://localhost/MySite/images/uk.gif" Dim strLoginURL As String = "http://localhost/MySite/login/login.aspx" 'first, request the login form to get the viewstate value Dim webReq As HttpWebRequest = DirectCast(WebRequest.Create(strLoginURL), HttpWebRequest) webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)" webReq.Credentials = New NetworkCredential(Me.ContainerForm.UserName, Me.ContainerForm.Password) Dim stmResponseReader As New StreamReader(webReq.GetResponse.GetResponseStream) Dim strResponseData As String = stmResponseReader.ReadToEnd stmResponseReader.Close() 'extract the viewstate value and build out POST data Dim strViewState As String = ExtractViewState(strResponseData) Dim postData As String = [String].Format("__VIEWSTATE={0}&txtUsername={1}&txtPassword={2}&btnLogin=Login", strViewState, Me.ContainerForm.UserName, Me.ContainerForm.Password) 'have a cookie container ready to receive the forms auth cookie Dim cookies As New CookieContainer 'now post to the login form webReq = DirectCast(WebRequest.Create(strLoginURL), HttpWebRequest) webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)" webReq.Credentials = New NetworkCredential(Me.ContainerForm.UserName, Me.ContainerForm.Password) webReq.Method = "POST" webReq.ContentType = "applicat