C# 远程服务器返回错误:(401) 未经授权

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2038808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:53:50  来源:igfitidea点击:

The remote server returned an error: (401) Unauthorized

c#.nethttp-status-code-401

提问by Zaidman

I'm trying to get the html code of certain webpage, I have a username and a password that are correct but i still can't get it to work, this is my code:

我正在尝试获取某个网页的 html 代码,我有一个正确的用户名和密码,但我仍然无法让它工作,这是我的代码:

private void buttondownloadfile_Click(object sender, EventArgs e)
{
    NetworkCredentials nc = new NetworkCredentials("?", "?", "http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");   
    WebClient client = new WebClient();

    client.Credentials = nc;
    String htmlCode = client.DownloadString("http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");

    MessageBox.Show(htmlCode);
}

The MessageBox is just to test it, the problem is that every time I get to this line:

MessageBox 只是为了测试它,问题是每次我到这一行时:

String htmlCode = client.DownloadString("http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");

I get an exception:

我得到一个例外:

The remote server returned an error: (401) Unauthorized.

远程服务器返回错误:(401) 未经授权。

How do I fix this?

我该如何解决?

回答by Rubens Farias

Try to create a NetworkCredentialwithout that domain part:

尝试创建一个NetworkCredential没有该域部分的:

NetworkCredential nc = new NetworkCredential("?", "?");   

回答by Sheikh Rahat Ali

I have tried the following code and it is working.

我已经尝试了以下代码并且它正在工作。

    private void Form1_Load(object sender, EventArgs e)        
    {
        try
        {
            // Create Request
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://192.168.0.181/axis-cgi/com/ptz.cgi?move=up");

            // Create Client
            WebClient client = new WebClient();

            // Assign Credentials
            client.Credentials = new NetworkCredential("root", "a");

            // Grab Data
            string htmlCode = client.DownloadString(@"http://192.160.0.1/axis-cgi/com/ptz.cgi?move=up");

            // Display Data
            MessageBox.Show(htmlCode);
        }
        catch (WebException ex) 
        {
            MessageBox.Show(ex.ToString());
        }
    }

回答by kad81

In my case client.UseDefaultCredentials = true;did the trick.

在我的情况下client.UseDefaultCredentials = true;成功了。