0

I need to accept self-signed SSL certificates while developing my C# .NET 4.0 code and I've used the following code from https://stackoverflow.com/a/18624335/1166898

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

I then call this method later in the code:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

When the connection is trusted, response.ContentLength returns the right length, however, when the connection is untrusted, response.ContentLength is -1. The actual content is right in both cases.

How can I get the correct response.ContentLength with an untrusted (self-signed) connection?

CJ Dennis
  • 4,226
  • 2
  • 40
  • 69

1 Answers1

0

I think your problem with response.ContentLength = -1 is not caused by the untrusted(self-signed) connection.

I tried the code with a local web app with self-signed certificate and the ContentLength had a positive value.

In the documentation the value -1 is simply because the

Content-Length header is not set in the response

https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.contentlength?redirectedfrom=MSDN&view=net-5.0#System_Net_HttpWebResponse_ContentLength

I tried this with stackoverflow url and ContentLength came back -1

    string url = "https://stackoverflow.com/";
    HttpWebRequest request = WebRequest.CreateHttp(url);
    request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
    
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Console.WriteLine($"Content length is : {response.ContentLength}");
yos
  • 9
  • 3
  • I think you're right, but I haven't been able to work out how to get Apache on Windows consistently return the `Content-Length`. I've asked a new question about it on [sf]. – CJ Dennis Oct 28 '21 at 13:34