ClientWebsocket SSL证书验证失败

问题描述

我正在用Xamarin.Forms编写一个针对.Net Standard 2.1的应用程序,主要侧重于Android版本。

我有一些websocket客户端代码可以连接到我的安全自签名服务器;但是,它不会验证证书。我发现一些引用使用ServicePointManager进行验证回调或ClientWebSocketoptions.RemoteCertificateValidationCallback,但在连接时都不会调用任何回调。 这是连接代码

public async Task Connect(string url) {
            if (client != null) {
                if (client.State == WebSocketState.Open) return;
                else client.dispose();
            }
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCert;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            client = new ClientWebSocket();
            client.Options.AddSubProtocol("json");
            client.Options.UseDefaultCredentials = false;
            client.Options.RemoteCertificateValidationCallback = ValidateServerCert;
            if (CTS != null) CTS.dispose();
            CTS = new CancellationTokenSource();
            Console.WriteLine("TBL: Connecting to " + url + "...");
            try {
                await client.ConnectAsync(new Uri(url),CTS.Token);
            } catch (Exception e) {
                Console.WriteLine("TBL: Ex: " + e);
            }
            Console.WriteLine("TBL: Client state: " + client.State);
            if (client.State == WebSocketState.Open) {
                OnConnect?.Invoke(); // if no callbacks registered,it's null
                Console.WriteLine("TBL: Websocket connected");
                await Task.Factory.StartNew(ReceiveLoop,CTS.Token,TaskCreationoptions.LongRunning,TaskScheduler.Default);
            }
        }

将其打印在设备日志中(我还不能嵌入图片):

Device Log Output

我已经在互联网上搜寻了答案/提示,并且大多数似乎适用于HTTPS,而不适用于Websocket(或者至少它们的解决方案似乎不起作用)。无论如何安排,我都无法调用验证回调。任何帮助将不胜感激。

解决方法

https://stackoverflow.com/a/26336847/9516

这接受所有证书,甚至是自签名的: ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };