我正在尝试访问同一域/同一 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");
}
我怀疑您尝试访问的网页使用表单身份验证。这意味着如果您希望能够访问受保护的资源,则必须提供有效的身份验证 cookie。为了获得有效的身份验证 cookie,您必须首先通过向发出 cookie 的登录页面发送 POST 请求来对自己进行身份验证。一旦您检索到 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 浏览器中进行身份验证,并使用 FireBug 查看需要发送的确切参数和标头。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)