【发布时间】:2012-12-20 18:54:12
【问题描述】:
我有一个运行 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;
}
}
我查看了以下相关问题,但没有一个问题有我能理解的最终解决方案。
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
任何帮助将不胜感激!
【问题讨论】:
标签: c# asp.net authentication webclient