.net Standard 1.3 意味着 -> 没有 WebProxy 库。所以我创建了一个,这里是:
public class WebProxy : IWebProxy, ISerializable
{
private readonly ArrayList _bypassList;
public WebProxy() : this((Uri)null, false, null, null) { }
public WebProxy(Uri Address) : this(Address, false, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
{
this.Address = Address;
this.Credentials = Credentials;
this.BypassProxyOnLocal = BypassOnLocal;
if (BypassList != null)
{
_bypassList = new ArrayList(BypassList);
UpdateRegExList(true);
}
}
private void UpdateRegExList(bool canThrow)
{
Regex[] regExBypassList;
ArrayList bypassList = _bypassList;
try
{
if (bypassList != null && bypassList.Count > 0)
{
regExBypassList = new Regex[bypassList.Count];
for (int i = 0; i < bypassList.Count; i++)
{
regExBypassList[i] = new Regex((string)bypassList[i], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
}
catch
{
if (!canThrow)
{
return;
}
throw;
}
}
public WebProxy(string Host, int Port)
: this(new Uri("http://" + Host + ":" + Port.ToString(CultureInfo.InvariantCulture)), false, null, null)
{
}
public WebProxy(string Address)
: this(CreateProxyUri(Address), false, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal)
: this(CreateProxyUri(Address), BypassOnLocal, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, Credentials)
{
}
public Uri Address { get; set; }
public bool BypassProxyOnLocal { get; set; }
public bool IsBypassed(Uri host)
{
return true;
}
public ICredentials Credentials { get; set; }
public bool UseDefaultCredentials
{
get { return Credentials == CredentialCache.DefaultCredentials; }
set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
}
private Uri proxyUri;
public Uri GetProxy(Uri destination)
{
return proxyUri;
}
private static Uri CreateProxyUri(string address) =>
address == null ? null :
address.IndexOf("://") == -1 ? new Uri("http://" + address) :
new Uri(address);
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
}
我像这样创建 HttpClient :
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy(proxy.Address, true, new string[0], proxy.Credentials),
UseProxy = true
};
HttpClient httpClient = new HttpClient(handler);
没有错误,没有例外,尽管这正是我正在寻找的。我使用 Fiddler 设置了一个代理,带有用户名和密码,为了测试代理,我有意将另一个密码传递给 httpClient。
现在,问题是 httClient 在尝试调用指定的 API 时应该抛出异常,因为代理的凭据是错误的。
我错过了什么?感觉 httpClient 甚至根本看不到代理,尽管在调试时我可以看到凭据被传递给处理程序并由 httpClient 包含。