我正在尝试使用无效证书连接到SignalR服务器.不出所料我收到以下错误:
System.Net.Http.HttpRequestException : An error occurred while sending the request.
----> System.Net.WebException : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
----> System.Security.Authentication.AuthenticationException : The remote certificate is invalid according to the validation procedure.
Run Code Online (Sandbox Code Playgroud)
使用正常的.Net,HttpClient您可以使用WebRequestHandler具有ServerCertificateValidationCallback委托的构造它,允许您更改证书验证行为.SignalR HttpClient似乎没有这个.
Erk*_*rel 11
你应该为ServerCertificateValidationCallback事件注册一个方法.
此代码只注册一个匿名方法,该方法在触发事件时返回true.
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
Run Code Online (Sandbox Code Playgroud)
小心,这是一个全球性的环境.所以所有ssl/tls请求signalr或http都将使用此设置.
小智 7
我相信我已经找到了一种似乎有效但不像通常推荐的 ServicePointManager.ServerCertificateValidationCallback 方法那样具有全局性的方法。我首先创建 SignalR“DefaultHttpClient”类的子类,如下所示:
class CustomHttpClient : DefaultHttpClient
{
private readonly System.Net.Security.RemoteCertificateValidationCallback _serverCertificateValidationCallback;
public CustomHttpClient (System.Net.Security.RemoteCertificateValidationCallback serverCertificateValidationCallback) : base()
{
this._serverCertificateValidationCallback = serverCertificateValidationCallback;
}
protected override HttpMessageHandler CreateHandler()
{
var rv = base.CreateHandler() as WebRequestHandler;
if (this._serverCertificateValidationCallback != null)
rv.ServerCertificateValidationCallback = this._serverCertificateValidationCallback;
return rv;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我在 HubConnection 实例上调用“Start”时,我可以使用我的自定义 HttpClient 实现,如下所示:
var hubConnection = new HubConnection("my server url");
var myHub = hubConnection.CreateHubProxy("my hub name");
hubConnection.Start(new CustomHttpClient((sender, certificate, chain, sslPolicyErrors) =>
{
//put some validation logic here if you want to.
return true;
}));
Run Code Online (Sandbox Code Playgroud)
这应该允许您按照您认为合适的方式验证服务器证书,但将范围保持在当前 HubConnection,而不是影响来自您的应用程序的所有 HTTP 流量。