Powershell 和 PowerShell Core 之间的 Net.HttpWebRequest 区别

Powershell 和 PowerShell Core 之间的 Net.HttpWebRequest 区别

希望有人能解释一下。在 Powershell 中,以下代码生成网站证书的输出:

$req = [Net.HttpWebRequest]::Create('https://www.google.com')
$req.GetResponse()
$req.Servicepoint.certificate

       Handle Issuer                                       Subject
       ------ ------                                       -------
2266454817712 CN=GTS CA 1O1, O=Google Trust Services, C=US CN=www.google.com...

在 Powershell Core 中,它返回一个空值/空白$req.Servicepoint.certificate

BindIPEndPointDelegate :
ConnectionLeaseTimeout : -1
Address                : https://www.google.com/
MaxIdleTime            : 100000
UseNagleAlgorithm      : True
ReceiveBufferSize      : -1
Expect100Continue      : True
IdleSince              : 20/09/2019 9:42:48 AM
ProtocolVersion        : 1.1
ConnectionName         : https
ConnectionLimit        : 2
CurrentConnections     : 0
Certificate            :
ClientCertificate      :
SupportsPipelining     : True

答案1

它看起来像.NET Core问题 36979很好地解释了这一点。

简而言之,系统.Net.HttpWeb请求已过时,在 .NET Core 中仅部分重新实现。特别是,ServicePoint 和 ServicePointManager 类存在但实际上不起作用。

他们建议迁移到系统.Net.Http.HttpClient相反,一位用户提供了以下代码示例来演示如何使用它检索证书。

using System;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace NetCoreConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = CustomCallback;
            var client = new HttpClient(handler);

            HttpResponseMessage response = client.GetAsync("https://www.google.com.mx/").GetAwaiter().GetResult();
            Console.WriteLine(response.StatusCode);
            Console.WriteLine((int)response.StatusCode);
        }

        private static bool CustomCallback(HttpRequestMessage arg1, X509Certificate2 arg2, X509Chain arg3, SslPolicyErrors arg4)
        {
            Console.WriteLine(arg2.GetEffectiveDateString());
            Console.WriteLine(arg2.GetExpirationDateString());
            Console.WriteLine(arg2.Issuer);
            Console.WriteLine(arg2.Subject);

            return arg4 == SslPolicyErrors.None;
        }
    }
}

答案2

如果有人感兴趣的话,以下是我为 PS Core 重新设计的方法:

$Req = [System.Net.Sockets.TcpClient]::new('www.google.com', '443')
$Stream = [System.Net.Security.SslStream]::new($Req.GetStream())
$Stream.AuthenticateAsClient('www.google.com')
$Stream.RemoteCertificate
$Stream.RemoteCertificate.GetExpirationDateString()

(ETC)

Ssl​Stream.​Remote​Certificate 属性

相关内容