我尝试使用无效证书连接到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.
使用正常的.Net HttpClient
,您可以使用具有WebRequestHandler
委托的ServerCertificateValidationCallback
构建它,允许您更改证书验证行为。 SignalR HttpClient
似乎没有这个。
答案 0 :(得分:10)
您应该为ServerCertificateValidationCallback
事件注册一个方法。
此代码只注册一个匿名方法,该方法在触发事件时返回true。
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
小心,这是一个全局设置。所以所有ssl / tls请求signalr或http都将使用此设置。
答案 1 :(得分:3)
我相信我找到了一种似乎有效的方法,但不像通常推荐的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;
}
}
现在我可以在调用" Start"时使用我自定义的HttpClient实现。在我的HubConnection实例上,如下所示:
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;
}));
这应该允许您根据需要验证服务器证书,但是将范围保留在当前的HubConnection中,而不是影响应用程序的所有HTTP流量。