2016-07-12 104 views
2

相对较新的C#,但取得了良好的进展。设置简单WebRequest的网络凭证

我目前正在尝试测试一个System.Net.WebRequest方法。使用有用的HTTP测试工具包https://httpbin.org/ - 我试图将网络凭证传递给https://httpbin.org/basic-auth/user/passwd并检索成功的连接。 (目前获得401的)

用户名是用户,密码是passwrd。

我有一个简单的表单,并启动请求的按钮。然而,正如所述,它不工作,我得到一个401错误。

这是我到目前为止有:

 private void button1_Click(object sender, EventArgs e) 
    { 

     NetworkCredential myCred = new NetworkCredential(
     "user", "passwrd", "https://httpbin.org"); 


     // Create a request for the URL. 
     WebRequest request = WebRequest.Create(
      "https://httpbin.org/basic-auth/user/passwd"); 
     // If required by the server, set the credentials. 
     request.Credentials = myCred; 
     // Get the response. 
     WebResponse response = request.GetResponse(); 
     // Display the status. 
     Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
     // Get the stream containing content returned by the server. 
     Stream dataStream = response.GetResponseStream(); 
     // Open the stream using a StreamReader for easy access. 
     StreamReader reader = new StreamReader(dataStream); 
     // Read the content. 
     string responseFromServer = reader.ReadToEnd(); 
     // Display the content. 
     Console.WriteLine(responseFromServer); 
     // Clean up the streams and the response. 
     reader.Close(); 
     response.Close(); 
    } 
+1

密码是'passwd'不'passwrd' ... – SimpleVar

+0

哈哈!这是一个好开始! - 我仍然收到错误。 – bushell

+0

我不认为域看起来像这样:“https://httpbin.org”。它必须是类似于“MYDOMAIN \ myusername” –

回答

2

问题是与您的凭据,你是假设domain是HTTP域,但这只是对于像Active Directory域有用。只是删除该参数(和固定密码),它会工作:

NetworkCredential myCred = new NetworkCredential("user", "passwd");