Use HttpClient to make secure HTTPS calls
Question:
When using HttpClient to make an HTTPS request, an error occurs: "The underlying connection was closed: Unable to establish trust for the SSL/TLS secure channel."
Solution:
To resolve this issue, please follow these steps:
Set security protocol:
Specify the TLS protocol used by default. Add the following lines to your code:
<code class="language-csharp">System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;</code>
Modify HttpClient code:
Modified HttpClient code to support HTTPS calls:
<code class="language-csharp">HttpClient httpClient = new HttpClient(); System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; httpClient.BaseAddress = new Uri("https://foobar.com/"); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/xml")); var task = httpClient.PostAsXmlAsync<devicerequest>("api/SaveData", request);</code>
Additional notes:
The above is the detailed content of How Can I Fix 'Could Not Establish Trust Relationship' Errors When Making HTTPS Calls with HttpClient?. For more information, please follow other related articles on the PHP Chinese website!