C# 中的代理基本身份验证:HTTP 407 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9603093/
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-09 08:05:21  来源:igfitidea点击:

Proxy Basic Authentication in C#: HTTP 407 error

c#proxyhttpwebrequestbasic-authenticationhttp-status-code-407

提问by rplusg

I am working with a proxy that requires authentication, i.e., in a browser if I try to open a page it will immediately ask for credentials. I supplied same credentials in my program but it fails with HTTP 407 error.

我正在使用需要身份验证的代理,即在浏览器中,如果我尝试打开一个页面,它会立即要求提供凭据。我在我的程序中提供了相同的凭据,但它因 HTTP 407 错误而失败。

Here is my code:

这是我的代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

IWebProxy proxy = WebRequest.GetSystemWebProxy();
CredentialCache cc = new CredentialCache();
NetworkCredential nc = new NetworkCredential();

nc.UserName = "userName";
nc.Password = "password";
nc.Domain = "mydomain";
cc.Add("http://20.154.23.100", 8888, "Basic", nc);
proxy.Credentials = cc;
//proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Proxy = proxy;
request.Proxy.Credentials = cc;
request.Credentials = cc;
request.PreAuthenticate = true;

I have tried every possible thing but seem like I am missing something. Is it something like, I have to make two requests? First with out credentials and once I hear back from server about need for credentials, make same request with credentials?

我已经尝试了所有可能的事情,但似乎我错过了一些东西。是不是我必须提出两个请求?首先没有凭据,一旦我从服务器听到需要凭据的消息,就用凭据发出相同的请求?

采纳答案by rplusg

here is the correct way of using proxy along with creds..

这是使用代理和信用的正确方法..

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

IWebProxy proxy = request.Proxy;                    
if (proxy != null)
{
    Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
    Console.WriteLine("Proxy is null; no proxy will be used");
}

WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://20.154.23.100:8888");
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
myProxy.Address = newUri;
// Create a NetworkCredential object and associate it with the 
// Proxy property of request object.
myProxy.Credentials = new NetworkCredential("userName", "password");
request.Proxy = myProxy;

Thanks everyone for help... :)

谢谢大家的帮助... :)

回答by tomfanning

This method may avoid the need to hard code or configure proxy credentials, which may be desirable.

这种方法可以避免对可能需要的硬编码或配置代理凭证的需要。

Put this in your application configuration file - probably app.config. Visual Studio will rename it to yourappname.exe.config on build, and it will end up next to your executable. If you don't have an application configuration file, just add one using Add New Item in Visual Studio.

把它放在你的应用程序配置文件中——可能是 app.config。Visual Studio 将在构建时将其重命名为 yourappname.exe.config,它会在您的可执行文件旁边结束。如果您没有应用程序配置文件,只需使用 Visual Studio 中的添加新项添加一个。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <defaultProxy useDefaultCredentials="true" />
  </system.net>
</configuration>

回答by Carl Onager

I was getting a very similar situation where the HttpWebRequest wasn't picking up the correct proxy details by default and setting the UseDefaultCredentials didn't work either. Forcing the settings in code however worked a treat:

我遇到了非常相似的情况,默认情况下 HttpWebRequest 没有获取正确的代理详细信息,并且设置 UseDefaultCredentials 也不起作用。然而,在代码中强制设置是一种享受:

IWebProxy proxy = myWebRequest.Proxy;
if (proxy != null) {
    string proxyuri = proxy.GetProxy(myWebRequest.RequestUri).ToString();
    myWebRequest.UseDefaultCredentials = true;
    myWebRequest.Proxy = new WebProxy(proxyuri, false);
    myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
}

and because this uses the default credentials it should not ask the user for their details.

并且由于它使用默认凭据,因此不应询问用户的详细信息。

回答by Robbo

This problem had been bugging me for years the only workaround for me was to ask our networks team to make exceptions on our firewall so that certain URL requests didn't need to be authenticated on the proxy which is not ideal.

这个问题多年来一直困扰着我,对我来说唯一的解决方法是要求我们的网络团队在我们的防火墙上设置例外,以便某些 URL 请求不需要在不理想的代理上进行身份验证。

Recently I upgraded the project to .NET 4 from 3.5 and the code just started working using the default credentials for the proxy, no hardcoding of credentials etc.

最近我将项目从 3.5 升级到 .NET 4,代码刚刚开始使用代理的默认凭据工作,没有对凭据进行硬编码等。

request.Proxy.Credentials = CredentialCache.DefaultCredentials;

回答by sansalk

try this

尝试这个

        var YourURL = "http://yourUrl/";

         HttpClientHandler handler = new HttpClientHandler() 
         { 
             Proxy = new WebProxy("http://127.0.0.1:8888"), 
             UseProxy = true, 
         }; 

         Console.WriteLine(YourURL); 

         HttpClient client = new HttpClient(handler); 

回答by MahmutKarali

You can use like this, it works!

你可以这样使用,它有效!

        WebProxy proxy = new WebProxy
        {
            Address = new Uri(""),
            Credentials = new NetworkCredential("", "")
        };

        HttpClientHandler httpClientHandler = new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true
        };

        HttpClient client = new HttpClient(httpClientHandler);

        HttpResponseMessage response = await client.PostAsync("...");