Last active
August 29, 2015 14:06
-
-
Save pmhsfelix/232ee8a51e17204a31d1 to your computer and use it in GitHub Desktop.
HttpWebRequest ServerCertificateValidationCallback and connection reuse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using System.Net.Security; | |
using System.Security.Cryptography.X509Certificates; | |
using Xunit; | |
namespace CertificateValidationAndConnections | |
{ | |
public class CertificateValidationAndConnectionsFacts | |
{ | |
private const int NoOfRequests = 10; | |
private static readonly Uri[] RequestUris = new [] | |
{ | |
new Uri("https://github.com/webapibook"), | |
new Uri("https://groups.google.com/forum/#!forum/webapibook") | |
}; | |
static CertificateValidationAndConnectionsFacts() | |
{ | |
ServicePointManager.DefaultConnectionLimit = 100; | |
} | |
public class UsingStaticValidator | |
{ | |
public void Run() | |
{ | |
var hwr = WebRequest.Create(RequestUris[0]) as HttpWebRequest; | |
hwr.ServerCertificateValidationCallback = StaticValidator; | |
var res = hwr.GetResponse(); | |
res.GetResponseStream().Close(); | |
} | |
private static bool StaticValidator(object sender, X509Certificate certificate, X509Chain chain, | |
SslPolicyErrors sslpolicyerrors) | |
{ | |
return sslpolicyerrors == SslPolicyErrors.None; | |
} | |
} | |
[Fact] | |
public void ConnectionsAreReused() | |
{ | |
for (var i = 0; i < NoOfRequests; ++i) | |
{ | |
new UsingStaticValidator().Run(); | |
} | |
// connection reuse: only one connection for all requests | |
Assert.Equal(1, ServicePointManager.FindServicePoint(RequestUris[0]).CurrentConnections); | |
} | |
public class UsingInstanceValidator | |
{ | |
public void Run() | |
{ | |
var hwr = WebRequest.Create(RequestUris[1]) as HttpWebRequest; | |
hwr.ServerCertificateValidationCallback = InstanceValidator; | |
var res = hwr.GetResponse(); | |
res.GetResponseStream().Close(); | |
} | |
private bool InstanceValidator(object sender, X509Certificate certificate, X509Chain chain, | |
SslPolicyErrors sslpolicyerrors) | |
{ | |
return sslpolicyerrors == SslPolicyErrors.None; | |
} | |
} | |
[Fact] | |
public void ConnectionsAreNotReused() | |
{ | |
for (var i = 0; i < NoOfRequests; ++i) | |
{ | |
new UsingInstanceValidator().Run(); | |
} | |
// no connection reuse: one new connection per request | |
Assert.Equal(NoOfRequests, ServicePointManager.FindServicePoint(RequestUris[1]).CurrentConnections); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment