Skip to content

Instantly share code, notes, and snippets.

@pmhsfelix
Last active August 29, 2015 14:06
Show Gist options
  • Save pmhsfelix/232ee8a51e17204a31d1 to your computer and use it in GitHub Desktop.
Save pmhsfelix/232ee8a51e17204a31d1 to your computer and use it in GitHub Desktop.
HttpWebRequest ServerCertificateValidationCallback and connection reuse
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