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?
RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.
The main conclusion is that one is not better than the other, and we shouldn't compare them since RestSharp is a wrapper around HttpClient. The decision between using one of the two tools depends on the use case and the situation.
The main purpose of RestSharp is to make synchronous and asynchronous calls to remote resources over HTTP.
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;
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;
This worked fine for me:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With