在Windows PowerShell中,我在配置文件中使用以下代码来强制所有cmdlet使用我的代理(例如Update-Help
等)
using namespace System.Net
using namespace System.Security.Principal
$isAdmin = ([WindowsPrincipal][WindowsIdentity]::GetCurrent()).IsInRole([WindowsBuiltInRole]::Administrator)
if ($isAdmin)
{
[WebRequest]::DefaultWebProxy = [WebProxy]::new('http://proxy:port')
[WebRequest]::DefaultWebProxy.Credentials = [CredentialCache]::DefaultNetworkCredentials
}
$wc = [WebClient]::new()
$wc.Proxy.Credentials = [CredentialCache]::DefaultNetworkCredentials
我还有其他代码来处理证书/ SSL:
@([Enum]::GetValues([SecurityProtocolType])).
Where{$PSItem -gt [Math]::Max(
[ServicePointManager]::SecurityProtocol.value__,
[SecurityProtocolType]::Tls.value__
)}.
ForEach{[ServicePointManager]::SecurityProtocol = [ServicePointManager]::SecurityProtocol -bor $PSItem}
[ServicePointManager]::ServerCertificateValidationCallback = {$true}
这可行,但是msdn documentation建议改用System.Net.Http.HttpClient
,因此我尝试在此处实现这些相同的想法:
using namespace System.Net
using namespace System.Security.Authentication
Add-Type -AssemblyName System.Net.Http, System.Net.Http.WebRequest
$handler = [System.Net.Http.WebRequestHandler]::new()
$handler.UseDefaultCredentials = $true
$handler.DefaultProxyCredentials = [CredentialCache]::DefaultNetworkCredentials
$handler.SslProtocols = [SslProtocols]::Tls12
$handler.ServerCertificateValidationCallback = {$true}
$http = [System.Net.Http.HttpClient]::new($handler, $true)
使用此代码的连接失败,提示我未传递代理凭据。我想知道这里交互的区别是什么,以便我进一步理解。