C# Asp.Net中HttpWebRequest.GetResponse连接关闭问题求助
Hey there! That connection error you're hitting is super common when dealing with sites that have strict security rules—let's break down how to fix it, focusing on the certificate and TLS issues you mentioned.
1. First: Update TLS Protocol Version
Most modern websites (especially those with tight security) require TLS 1.2 or higher, but older .NET frameworks default to outdated TLS versions like 1.0. Add this line before creating your HttpWebRequest:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
This ensures your request uses the latest supported TLS versions, which often resolves the closed connection issue immediately.
2. Handle Certificate Validation
If the target site uses a self-signed certificate, or one that isn't trusted by your server's root certificate store, you'll need to adjust how your request validates the certificate.
Option A: Temporary Skip (Testing Only!)
If you're just testing and fully trust the site, you can temporarily bypass certificate validation. Never use this in production—it exposes you to security risks:
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
Option B: Trust a Specific Certificate (Production-Safe)
For production, instead of skipping validation, verify that the site's certificate matches a trusted one. Get the certificate's hash from the site's SSL details in your browser, then use this logic:
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => { // Replace with the SHA-1/SHA-256 hash of the target site's certificate string trustedCertificateHash = "A1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0"; return cert.GetCertHashString().Equals(trustedCertificateHash, StringComparison.OrdinalIgnoreCase); };
Option C: Install the Certificate to Trusted Store
The most secure production fix is to install the site's root certificate into your server's Trusted Root Certification Authorities store. This way, HttpWebRequest will automatically trust it without any code changes.
3. Additional Tweaks to Avoid Connection Issues
Sometimes other request settings can trigger this error—add these to your request setup:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://your-specific-site.com"); // Mimic a browser user agent (some sites block non-browser requests) request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"; // Disable keep-alive to avoid lingering connection issues request.KeepAlive = false; // Handle compressed responses (many sites use gzip/deflate) request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Full Modified Button Click Example
Here's how all this fits into your Button1_Click event:
protected void Button1_Click(object sender, EventArgs e) { try { // Set supported TLS versions first ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; // Add certificate validation logic (choose one option above) ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslErrors) => { // For testing only: skip validation return true; // For production: use hash validation instead // string trustedHash = "YOUR_CERT_HASH"; // return cert.GetCertHashString().Equals(trustedHash, StringComparison.OrdinalIgnoreCase); }; // Create and configure the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://your-specific-site.com"); request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"; request.KeepAlive = false; request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // Get and process the response using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string responseContent = reader.ReadToEnd(); // Do something with the response here } } catch (Exception ex) { // Handle exceptions (log details for debugging) Console.WriteLine($"Error: {ex.Message}\nStack Trace: {ex.StackTrace}"); } }
Remember: Always prioritize secure certificate validation in production—skipping checks should only be for local testing.
内容的提问来源于stack exchange,提问作者Raniel Quirante

