Changing security protocol per request (HttpClient)

asp.net-web-api, c#, http, ssl

Solution

You don't need to set it.

You can use:

using System.Net;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

Additional Notes:

- Needed for .Net 4.5 because Tls12 is not a default protocol.

- Need to write the above code only once within the application. (For example within Global.asax > Application_Start within Web application or equivalent in Winforms application)

- For .Net 4.6 and above, Tls12 is a default protocol so it is not needed

Problem

I've got a Web API that must communicate with a few different services. Currently, I have the Web API set to use the following security protocol: `ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;` When the API calls out to another service via `HttpClient` (say like Twitter), it will use that protocol. At the same time however, another request may come in to access something from the cloud, which for whatever reason, currently requires TLS (not TLS 1.2). The request to the cloud, before firing out, sets the security protocol again: `ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;` The problem I'm running into is when two separate and unique requests come in, one for Twitter and one for the cloud, the security protocol could switch over to the "wrong one" before it's sent out, causing the request to fail. Is there a way to set the security protocol on the `HttpClient` per request so that I'm not swapping around a setting in some singleton somewhere?

Original source