我正在尝试访问受登录表单保护的页面。我已经检查了SO中的主题,我发现了WebClient的这个扩展,它使用了cookie:
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
{
this.CookieContainer = new CookieContainer();
}
public CookieContainer CookieContainer { get; private set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = this.CookieContainer;
}
return request;
}
}
在互联网的帮助下,我提出了一些代码:
using (var webClient = new CookieAwareWebClient())
{
try
{
NameValueCollection collection = new NameValueCollection
{
{"UserName", userName},
{"Password", password}
};
webClient.UploadValues("https://judge.softuni.bg/Account/Login", "POST", collection);
string result = webClient.DownloadString("https://judge.softuni.bg/Contests/Compete/Results/Simple/104");
}
catch (WebException webException)
{
MessageBox.Show(webException.Status.ToString());
}
}
最后在“结果”字符串中我有一个带有表单操作的登录页面,如果我登录,它会将我重定向到想要的页面。任何想法我做错了什么?