24

When use RestSharp to call an API I get this error:

The underlying connection was closed: An unexpected error occurred on a send.

I've verified that my client ID, secret, username, and password are correct. I'm able to do this without issues in PowerShell.

public string GetTokenForBrightIdea()
{
    RestClient restclient = new RestClient(_uri);
    RestRequest request = new RestRequest() { Method = Method.POST };

    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
    request.AddParameter("grant_type", "password");
    request.AddParameter("client_id", _clientId);
    request.AddParameter("client_secret", _clientSecret);
    request.AddParameter("username", _clientUsername);
    request.AddParameter("password", _clientPassword);

    var tResponse = restclient.Execute(request);
    var responseJson = tResponse.Content;
    return JsonConvert.DeserializeObject<Dictionary<string, object>>(
        responseJson)["access_token"].ToString();
}

What am I missing when using RestSharp to make this work?

1
  • Look at this request in Fiddler, and look at the request you made from Powershell. Compare the two. See what's different, identify what you need to change. Commented Jan 31, 2018 at 18:53

3 Answers 3

49

So it turns out that because this call was HTTPS i needed to add the following line of code

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Sign up to request clarification or add additional context in comments.

1 Comment

Adding the security protocol to tls12 resolved the problem
11

For .Net 3.5 and 4.0 you could try putting this line of code prior to the initialization of the RestSharp client:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;

1 Comment

This worked wonders after such frustrating periiod of exploring! Has to be included for ,net framework 4.0 (maybe 3.5 too) whether it's rest sharp client, or a Web client!
2

This worked fine for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.