WebRequest
HTTPS
SSL
encrypted site
access

How do I use WebRequest to access an SSL encrypted site using HTTPS?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

To access an HTTPS site with WebRequest (or HttpWebRequest) in C# .NET, you typically just use an https:// URL and .NET handles TLS negotiation automatically. However, issues arise when the server uses a self-signed certificate, an expired certificate, or when the .NET framework's default TLS version is too old. The most common fix is setting ServicePointManager.SecurityProtocol to TLS 1.2 or higher. For modern .NET (5+), consider using HttpClient instead of WebRequest, as WebRequest is obsolete.

Basic HTTPS Request

csharp
1using System;
2using System.IO;
3using System.Net;
4
5// Simple HTTPS request — works when the certificate is valid
6var request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
7request.Method = "GET";
8
9using var response = (HttpWebResponse)request.GetResponse();
10using var reader = new StreamReader(response.GetResponseStream());
11string content = reader.ReadToEnd();
12Console.WriteLine(content);

If the server has a valid certificate from a trusted CA, this works without any additional configuration.

Fix: Set TLS Version

Older .NET Framework versions (4.5 and below) default to SSL 3.0 / TLS 1.0, which many servers reject. Set the protocol explicitly:

csharp
1// Set before making any requests
2ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
3
4// Then make your request
5var request = WebRequest.Create("https://api.example.com/data");
6using var response = request.GetResponse();
csharp
1// .NET Framework version requirements:
2// TLS 1.1: .NET 4.5+
3// TLS 1.2: .NET 4.5+ (must set explicitly), .NET 4.7+ (default)
4// TLS 1.3: .NET 4.8+ / .NET Core 3.0+
5
6// For .NET Framework 4.5-4.6.2, always set explicitly:
7ServicePointManager.SecurityProtocol =
8    SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
9
10// For .NET 4.7+ and .NET 6+, TLS 1.2 is the default

Handling Self-Signed Certificates

csharp
1// DEVELOPMENT ONLY — accept all certificates
2// This bypasses certificate validation entirely
3ServicePointManager.ServerCertificateValidationCallback =
4    (sender, certificate, chain, sslPolicyErrors) => true;
5
6var request = WebRequest.Create("https://self-signed.example.com");
7using var response = request.GetResponse();

Never use this in production. It disables certificate validation, making the connection vulnerable to man-in-the-middle attacks.

Validate a Specific Certificate

csharp
1// Accept only a specific certificate thumbprint
2ServicePointManager.ServerCertificateValidationCallback =
3    (sender, certificate, chain, sslPolicyErrors) =>
4    {
5        if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
6            return true;
7
8        // Accept a known self-signed certificate
9        string expectedThumbprint = "A1B2C3D4E5F6...";
10        return certificate?.GetCertHashString() == expectedThumbprint;
11    };

Adding Client Certificates

Some APIs require mutual TLS (mTLS) — the client presents a certificate to the server:

csharp
1var request = (HttpWebRequest)WebRequest.Create("https://secure-api.example.com");
2
3// Load client certificate from file
4var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(
5    "client-cert.pfx", "password");
6request.ClientCertificates.Add(cert);
7
8// Or load from the Windows certificate store
9var store = new System.Security.Cryptography.X509Certificates.X509Store(
10    StoreName.My, StoreLocation.CurrentUser);
11store.Open(OpenFlags.ReadOnly);
12var certs = store.Certificates.Find(
13    X509FindType.FindBySubjectName, "MyClientCert", false);
14request.ClientCertificates.Add(certs[0]);
15store.Close();
16
17using var response = request.GetResponse();

POST Request Over HTTPS

csharp
1ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
2
3var request = (HttpWebRequest)WebRequest.Create("https://api.example.com/login");
4request.Method = "POST";
5request.ContentType = "application/json";
6
7string jsonBody = "{\"username\":\"alice\",\"password\":\"secret\"}";
8byte[] bodyBytes = System.Text.Encoding.UTF8.GetBytes(jsonBody);
9request.ContentLength = bodyBytes.Length;
10
11using (var stream = request.GetRequestStream())
12{
13    stream.Write(bodyBytes, 0, bodyBytes.Length);
14}
15
16using var response = (HttpWebResponse)request.GetResponse();
17Console.WriteLine($"Status: {response.StatusCode}");

Modern Alternative: HttpClient

WebRequest is obsolete in .NET 6+. Use HttpClient instead:

csharp
1using System.Net.Http;
2
3// HttpClient handles TLS automatically
4var client = new HttpClient();
5string content = await client.GetStringAsync("https://api.example.com/data");
6
7// POST with JSON
8var json = new StringContent("{\"key\":\"value\"}", System.Text.Encoding.UTF8, "application/json");
9var response = await client.PostAsync("https://api.example.com/data", json);
10
11// Custom certificate validation with HttpClient
12var handler = new HttpClientHandler
13{
14    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
15};
16var client2 = new HttpClient(handler);
csharp
1// HttpClient with client certificate
2var handler = new HttpClientHandler();
3handler.ClientCertificates.Add(new X509Certificate2("client.pfx", "password"));
4
5var client = new HttpClient(handler);
6var response = await client.GetAsync("https://mtls-api.example.com");

Common Pitfalls

  • Not setting SecurityProtocol before the first request: ServicePointManager.SecurityProtocol must be set before any WebRequest is created. Setting it after the first request has no effect on already-established connections. Set it at application startup.
  • Using ServerCertificateValidationCallback = true in production: Accepting all certificates disables TLS security entirely. An attacker can intercept traffic with any certificate. Only use this for local development with self-signed certificates.
  • Forgetting that WebRequest is obsolete: In .NET 6+, WebRequest and HttpWebRequest are marked as obsolete. Use HttpClient for new code. HttpClient is also more efficient because it reuses connections.
  • Creating a new HttpClient per request: HttpClient is designed to be reused. Creating a new instance per request exhausts socket connections (socket exhaustion). Use a single HttpClient instance or IHttpClientFactory in ASP.NET Core.
  • TLS errors with older Windows versions: Windows 7 and Server 2008 R2 do not support TLS 1.2 by default without a Windows update. If your application runs on old OS versions, ensure the TLS 1.2 update (KB3140245) is installed.

Summary

  • Use https:// URLs with WebRequest.Create() — .NET handles TLS automatically for valid certificates
  • Set ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 for .NET Framework 4.5-4.6.2
  • For self-signed certificates, use ServerCertificateValidationCallback (development only)
  • For client certificates (mTLS), add them to request.ClientCertificates
  • Migrate to HttpClient for .NET 6+ — WebRequest is obsolete
  • Always set TLS protocol and certificate callbacks at application startup, before any requests

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design