简体   繁体   English

为简单WebRequest设置网络凭据

[英]Setting Network Credentials for Simple WebRequest

Relatively new to C#, but making good progress. 相对较新的C#,但取得了良好的进展。

I'm currently trying to test a System.Net.WebRequest method. 我目前正在尝试测试System.Net.WebRequest方法。 Using the useful http testing kit at https://httpbin.org/ - I am trying to pass network credentials to https://httpbin.org/basic-auth/user/passwd and to retrieve a successful connection. 使用https://httpbin.org/上有用的http测试工具包 - 我正在尝试将网络凭据传递给https://httpbin.org/basic-auth/user/passwd并检索成功的连接。 (Currently getting 401's) (目前获得401的)

The username is user, and the password is passwrd. 用户名是user,密码是passwrd。

I have a simple form, and button which starts the request. 我有一个简单的表单,以及启动请求的按钮。 However, as stated, its not working, and i'm getting a 401 error. 但是,如上所述,它不起作用,我得到401错误。

Here is what I have so far: 这是我到目前为止:

        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();
    }

The problem is with your credentials, you are assuming that domain is the HTTP domain, but that's only useful for something like Active Directory domains. 问题在于您的凭据,您假设该domain是HTTP域,但这仅对Active Directory域之类的内容有用。 Just remove that parameter (and fix the password) and it will work: 只需删除该参数(并修复密码),它就会起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM