【问题标题】:Setting Network Credentials for Simple WebRequest为简单 WebRequest 设置网络凭据
【发布时间】:2016-07-12 10:19:44
【问题描述】:

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

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

用户名是user,密码是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();
    }

【问题讨论】:

  • 密码是passwd 不是passwrd...
  • 哈哈!这是一个好的开始! - 我仍然收到错误消息。
  • 我认为域看起来不像:“httpbin.org”。它必须类似于“MYDOMAIN\myusername”
  • 试试不带主机参数的NetworkCredentials。还可以尝试req.CachePolicy = new..(NoCacheNoStore); 以确保您确实从之前的尝试中获得了非缓存响应。
  • 谢谢 SimpleVar。删除域对我有用,我现在收到一条成功消息。感谢您的帮助。

标签: c# https


【解决方案1】:

问题在于您的凭据,您假设 domain 是 HTTP 域,但这仅对 Active Directory 域等有用。只需删除该参数(并修复密码)即可:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    相关资源
    最近更新 更多