为什么使用 .NET Core 2 证书为空,但它在 .NET Framework 4.6.2 中工作得很好



我一直在做一些将.NET Framework 4.6.2应用程序迁移到.NET Core 2的测试。我注意到这个特定的应用程序,监控 http 在 Net Core 2 中无法正常工作。你能帮我验证发生了什么吗?

static void Main(string[] args)
        {
            try
            {
                HttpWebRequest myhttpWebReqest = (HttpWebRequest)WebRequest.Create("https://www.google.com.mx/");
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myhttpWebReqest.GetResponse();
            timer.Stop();
            TimeSpan timeSpan = timer.Elapsed;
            Console.WriteLine(timeSpan.ToString());
            Console.WriteLine();
            Console.WriteLine(myHttpWebResponse.StatusCode);
            Console.WriteLine((int)myHttpWebResponse.StatusCode);
            Console.WriteLine();
            Console.WriteLine(myhttpWebReqest.ServicePoint.Certificate.GetEffectiveDateString());
            Console.WriteLine();
            Console.WriteLine(myhttpWebReqest.ServicePoint.Certificate.GetExpirationDateString());
            Console.WriteLine();
            Console.WriteLine(myhttpWebReqest.ServicePoint.Certificate.Issuer);
            Console.WriteLine();
            Console.WriteLine(myhttpWebReqest.ServicePoint.Certificate.Subject);                
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            if(ex.InnerException !=null)
            {
                Console.WriteLine(ex.InnerException);
            }
        }
        Console.ReadLine();
    }
}

在.NET Framework 4.6.2中,我看到证书数据,在.NET Core 2中,我看到myhttpWebReqest.ServicePoint.Certificate null ...你知道为什么吗?

请参阅此处的讨论:https://github.com/dotnet/corefx/issues/36979

ServicePointManager 和 ServicePoint 类在 .NET Core 上是无操作的。 但是你可以用HttpClient做类似的事情。 HttpClient是.NET Framework和.NET Core中更现代和首选的HTTP API。

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;
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新