mko*_*mko 24 c# asp.net webclient credentials defaultnetworkcredentials
我正在尝试访问同一域/同一个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");
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 52
我怀疑您尝试访问的网页使用表单身份验证.这意味着,如果您希望能够访问受保护资源,则必须提供有效的身份验证cookie.并且为了获得有效的身份验证cookie,您必须首先通过向发出cookie的LogOn页面发送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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用此客户端触发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");
}
Run Code Online (Sandbox Code Playgroud)
显然,由于ASP.NET的ViewState琐事,您可能需要在登录请求中发送一些其他参数.以下是您可以执行的操作:在Web浏览器中进行身份验证,并使用FireBug查看需要发送的确切参数和标头.
归档时间: |
|
查看次数: |
69497 次 |
最近记录: |