WebClient访问具有凭据的页面

我正在尝试访问同一个域/同一个asp.net应用程序的网页,这是受密码保护的。 对于发起此呼叫的网页和正在访问的网页,凭据都是相同的。

这是代码,我不知道为什么我总是以登录表单html代码结束?

using (WebClient client = new WebClient()) { client.QueryString.Add("ID", "1040"); //add parameters //client.Credentials = CredentialCache.DefaultCredentials; //I tried to add credentials like this client.Credentials = new NetworkCredential("username", "password"); string htmlCode = client.DownloadString("http://domain.loc/testpage.aspx"); } 

我怀疑您尝试访问的网页使用表单身份validation。 这意味着,如果您希望能够访问受保护资源,则必须提供有效的身份validationcookie。 并且为了获得有效的身份validationcookie,您必须首先通过向发出cookie的LogOn页面发送POST请求来对自己进行身份validation。 一旦您检索到cookie,您就可以在受保护资源的后续请求中发送它。 您还应该注意到, WebClient开箱即用,不支持cookie。 因此,您可以编写自定义Cookie感知Web客户端:

 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; } } 

现在您可以使用此客户端触发2个请求:

 using (var client = new CookieAwareWebClient()) { var values = new NameValueCollection { { "username", "john" }, { "password", "secret" }, }; client.UploadValues("http://domain.loc/logon.aspx", values); // If the previous call succeeded we now have a valid authentication cookie // so we could download the protected page string result = client.DownloadString("http://domain.loc/testpage.aspx"); } 

显然,由于ASP.NET的ViewState琐事,您可能需要在登录请求中发送一些其他参数。 以下是您可以执行的操作:在Web浏览器中进行身份validation,并使用FireBug查看需要发送的确切参数和标头。