2012-07-06 74 views
0

我尝试登录到与C#WebClient的一个论坛,以取得userrelevant信息 我的问题是登录失败 我试图通过邮寄登录与Web客户端(cookieaware)论坛失败

我实际的代码提交所有需要的数据:获得所需

 var url = new Uri("http://www.hardwareluxx.de/community/"); 
     string user = Properties.Resources.username; 
     string pass = Properties.Resources.password; 
     var client = new CookieAwareWebClient(); 
     client.BaseAddress = @"http://www.hardwareluxx.de/community/"; 


     var document = new HtmlDocument(); 
     document.Load(new MemoryStream(client.DownloadData("index.php"))); 

     postData = new NameValueCollection(); 

     postData.Add("vb_login_username", user); 
     postData.Add("cookieuser", "1"); 
     postData.Add("vb_login_password", ""); 
     postData.Add("s", ""); 
     postData.Add("securitytoken", "guest"); 
     postData.Add("do", "login"); 
     postData.Add("vb_login_md5password", GetMd5Hash(pass)); 
     postData.Add("vb_login_md5password_utf", GetMd5Hash(pass)); 

     document.Load(new MemoryStream(client.UploadValues(url + "login.php?do=login", postData))); 

和一个小的帮扶方法MD5哈希值进行登录:

public static string GetMd5Hash(string TextToHash) 
    { 
     //Prüfen ob Daten übergeben wurden. 
     if (string.IsNullOrEmpty(TextToHash)) 
     { 
      return string.Empty; 
     } 

     //MD5 Hash aus dem String berechnen. Dazu muss der string in ein Byte[] 
     //zerlegt werden. Danach muss das Resultat wieder zurück in ein string. 
     MD5 md5 = new MD5CryptoServiceProvider(); 
     byte[] textToHash = Encoding.Default.GetBytes(TextToHash); 
     byte[] result = md5.ComputeHash(textToHash); 

     return BitConverter.ToString(result); 
    } 

和Web客户端其中cookie被存储,以及:

public class CookieAwareWebClient : WebClient 
{ 
    private readonly CookieContainer _cookie = new CookieContainer(); 

    protected override WebRequest GetWebRequest(Uri address) 
    { 
     WebRequest request = base.GetWebRequest(address); 
     if (request is HttpWebRequest) 
     { 
      (request as HttpWebRequest).CookieContainer = _cookie; 
     } 
     return request; 
    } 
} 

回答

0

你应该使用request.Credentials

public class CookieAwareWebClient : WebClient 
{ 
    private readonly CookieContainer _cookie = new CookieContainer(); 
    private string userName; 
    private string password; 

    public CookieAwareWebClient(string user, string pass) 
    { 
    userName = user; 
    password = pass; 
    } 

    protected override WebRequest GetWebRequest(Uri address) 
    { 
    WebRequest request = base.GetWebRequest(address); 

    if (!string.IsNullOrEmpty(userName)) 
    { 
     request.Credentials = new NetworkCredential(userName, password); 
    } 

    if (request is HttpWebRequest) 
    { 
     (request as HttpWebRequest).CookieContainer = _cookie; 
    } 

    return request; 
    } 
} 
string user = Properties.Resources.username; 
string pass = Properties.Resources.password; 

var client = new CookieAwareWebClient(user, pass);
凭据传递到HttpWebRequest的实例