Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

c# - How to specify SSL protocol to use for WebClient class

I have an application that sends data to a server using an HTTPS POST. I use a System.Net.WebClient object to do this. Here is a function that sends some data:

    private byte[] PostNameValuePairs(string uri, NameValueCollection pairs)
    {
        byte[] response;
        String responsestring = "";
        using (WebClient client = new WebClient())
        {
            client.Headers = GetAuthenticationHeader();

            string DataSent = GetNameValueCollectionValuesString(pairs);

            try
            {
                response = client.UploadValues(uri, pairs);
                responsestring = Encoding.ASCII.GetString(response);
            }
            catch (Exception e)
            {
                responsestring = "CONNECTION ERROR: " + e.Message;
                return Encoding.ASCII.GetBytes(responsestring);
            }
            finally
            {
                _communicationLogger.LogCommunication(uri, client.Headers.ToString(), DataSent, responsestring);
            }
        }

        return response;
    }

We are passing in a URI beginning with https://

This has been working great for a long time. Today, we started getting the following connection error: "The underlying connection was closed: An unexpected error occurred on a send". We did some troubleshooting with the owner of the server, and they finally narrowed it down to the following. They made a change to their server to block TLS 1.0, and said that we now need to send our data using either TLS 1.1 or 1.2.

What do I need to set in my WebClient object (or elsewhere in my function) to make it use TLS 1.1 or 1.2 instead of TLS 1.0?

We are using .NET Framework 4.5 if that makes a difference.

question from:https://stackoverflow.com/questions/30491716/how-to-specify-ssl-protocol-to-use-for-webclient-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the suggested other questions, I was able to solve it by adding the following line to my code:

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

This disabled TLS 1.0 from the client, and then the server accepted the connection.

Hope this helps someone else with the same issue. Although the answer is similar to those other questions, it wasn't obvious from the questions asked that this was the case, so I don't feel that this is a duplicate.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...