为简单 Web 请求设置网络凭据

本文关键字:网络 设置 请求 简单 Web | 更新日期: 2023-09-27 17:56:36

对C#来说相对较新,但进展良好。

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

用户名为用户,密码为通行证。

我有一个简单的表单和启动请求的按钮。 但是,如前所述,它不起作用,并且我收到 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();
    }

为简单 Web 请求设置网络凭据

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

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