I have a website running asp.net 2.0 with url authentication. There is a protected region of the website that requires users to log in to gain access to protected files. Is it possible to do the same thing using a System.Net.WebClient object to download a file in the protected area?
If you try to manually type in the url to a protected file, resource, page, etc it forwards you to the login page. I also get the html for the login page inside of “protectedFile.zip” whenever I execute the code below.
public void test()
{
try
{
using (var client = new CookieAwareWebClient())
{
//Not sure which name values to include, so I used what was in the post output in Firefox's firebug.
var values = new NameValueCollection
{
{ "ctl00$ContentPlaceHolder1$Login1$UserName", "testUsername" },
{ "ctl00$ContentPlaceHolder1$Login1$Password", "testPassword" }
};
retValue = client.UploadValues("www.test.com/login.aspx", values);
//retValue contains the login page?
Console.WriteLine(ASCIIEncoding.ASCII.GetString(retValue));
// If the previous call succeeded we now have a valid authentication cookie??
client.DownloadFile("www.test.com/protected/protectedFile.zip", "protectedFile.zip");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
Console.WriteLine(ASCIIEncoding.ASCII.GetString(retValue));
}
}
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
{
CookieContainer = new CookieContainer();
}
public CookieContainer CookieContainer { get; private set; }
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}
I have looked at the following related questions but none of them have a final solution that I can understand.
asp.net Download files from protected server
How do I authenticate a WebClient request?
WebClient accessing page with credentials
Can't login into asp.net website with WebClient
Any help would be appreciated!
If you are trying to “spoof” an ASP.Net Web Forms
Postback, you will run into issues that will prevent you from doing so. You have to deal withVIEWSTATEandEVENTVALIDATION