Tuesday 9 April 2013

Downloading files from a site, which uses FBA

I had a requirement where I was suppose to download some files from the URL provided by client. I wrote a simple console app for this, provided the login credentials and downloaded the files. It looked quite simple and everything went well until I observed something fishy in downloaded files.

All the files were of same size. When I opened the files, I saw that it contains the login page of the site, and not exactly the content of the file :(.

Where exactly I went wrong?

The site provided by the client was not using windows authentication (for which I wrote the code), but it was using Form based Authentication.

So, next question, How to convert my console app to other form so that it can download the files from site using FBA?

Here is how I did that:

1. Write a class which inherits from WebClient class and overwrite GetWebRequest method.

public class OverWrittenWebClient : WebClient
{
        private CookieContainer cookie = new CookieContainer();
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            try
            {
                if (request is HttpWebRequest)
                {
                    (request as HttpWebRequest).CookieContainer = cookie;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR : " + ex.Message);
            }
            return request;
        }
}

2. Use this class' object for downloading the files, as shown below:


var client = new OverWrittenWebClient();
client.BaseAddress = @"<login page url>";
var loginData = new NameValueCollection();
loginData.Add("<loginID field name>", "<loginID>");
loginData.Add("<password field name>", "<Password>");
client.UploadValues(client.BaseAddress, "POST", loginData);
client.DownloadFile("<url of file>", "<download file location>");

3. "<loginID field name>" and "<password field name>" can be obtained by right clicking and then clicking on "view source" link of login page and then finding the ID for login text box and password text box respectively.

No comments:

Post a Comment