为Simple WebRequest设置网络凭据

4

我对C#比较新,但进展顺利。

我目前正在尝试测试一个System.Net.WebRequest方法。使用有用的http测试工具https://httpbin.org/ - 我正在尝试传递网络凭据到https://httpbin.org/basic-auth/user/passwd并检索成功的连接。(目前收到401错误)

用户名为user,密码为passwd。

我有一个简单的表单和按钮来启动请求。然而,正如所述,它没有起作用,我得到了一个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
哈哈!这是个好的开始!- 不过我还是在遇到错误。 - bushell
我认为域名不应该是这样的:"https://httpbin.org"。它应该像是"MYDOMAIN\myusername"这样的东西。 - user6522773
1
尝试使用没有主机参数的 NetworkCredentials。同时尝试 req.CachePolicy = new..(NoCacheNoStore); 确保您确实从之前的尝试中获得了非缓存响应。 - SimpleVar
谢谢SimpleVar。删除域名对我有用,现在我收到了成功的消息。感谢您的帮助。 - bushell
1个回答

3

问题出在您的凭据上,您假设domain 是HTTP域名,但这只对类似于Active Directory域的东西有用。只需删除该参数(并修复密码),它就会起作用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接