我有一个运行带有 url 身份验证的 asp.net 2.0 的网站。网站有一个受保护的区域,要求用户登录才能访问受保护的文件。是否可以使用 System.Net.WebClient 对象在受保护区域中下载文件来做同样的事情?
如果您尝试手动输入受保护文件、资源、页面等的 url,它会将您转发到登录页面。每当我执行下面的代码时,我也会在“protectedFile.zip”中获取登录页面的 html。
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;
}
}
我查看了以下相关问题,但没有一个有我能理解的最终解决方案。
任何帮助,将不胜感激!