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?

Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
Funkel
  • 133
  • 1
  • 6
  • 21
  • 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. –  Jan 31 '18 at 18:53

3 Answers3

46

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;
Funkel
  • 133
  • 1
  • 6
  • 21
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;
John Meyer
  • 2,296
  • 1
  • 31
  • 39
  • 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! – sanrnsam7 Mar 18 '21 at 13:15
2

This worked fine for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
Anjan Kant
  • 4,090
  • 41
  • 39