2016-01-24 57 views
1

這裏是我的WebClient類:WebClient的UploadValuesTaskAsync

class MyWebClient : WebClient 
{ 
    private CookieContainer _cookieContainer = new CookieContainer(); 
    public MyWebClient(string url, string login, string password) 
    { 
     var data = new NameValueCollection 
      { 
       { "username", login}, 
       { "password", password} 
      }; 
     UploadValues(new Uri(url), data); 
    } 
    protected override WebRequest GetWebRequest(Uri address) 
    { 
     WebRequest request = base.GetWebRequest(address); 
     if (request is HttpWebRequest) 
     { 
      (request as HttpWebRequest).CookieContainer = _cookieContainer; 
     } 
     return request; 
    } 
} 

這裏是樣品,我要如何使用它:

private MyWebClient _client; 

private void btnLogin_Click(object sender, RoutedEventArgs e) 
{ 
    _client = new MyWebClient("http://website/login.php", "account", "pw"); 
} 

private async void btnContent_Click(object sender, RoutedEventArgs e) 
{ 
    _client = await _client.DownloadStringTaskAsync("http://website"); 
} 

我的問題是..這個MyWebClient類,怎麼能我登錄異步? 我希望有人能幫助我,謝謝!

+0

你不能用'UploadValuesAsync'和將它移到構造函數之外? –

回答

1

您可以將登錄邏輯構造外,並使用UploadValuesTaskAsync方法是這樣的:

class MyWebClient : WebClient 
{ 
    //... 
    private readonly string m_Uri; 
    private readonly string m_Login; 
    private readonly string m_Password; 

    public MyWebClient(string url, string login, string password) 
    { 
     m_Password = password; 
     m_Login = login; 
     m_Uri = url; 
    } 

    public async Task LogIn() 
    { 
     var data = new NameValueCollection 
     { 
      {"username", m_Login}, 
      {"password", m_Password} 
     }; 
     await UploadValuesTaskAsync(new Uri(m_Uri), data); 
    } 

    //... 
} 

,然後用它是這樣的:

private async void btnLogin_Click(object sender, RoutedEventArgs e) 
{ 
    _client = new MyWebClient("http://website/login.php", "account", "pw"); 
    await _client.LogIn(); 
} 
+0

作品完美,謝謝雅各布馬薩德! – nrkz

+0

不客氣 –