Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API is returning error when using RESTSHARP

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?

like image 843
Funkel Avatar asked Jan 31 '18 18:01

Funkel


People also ask

What is RestSharp API?

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.

Is RestSharp better than HttpClient?

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.

Is RestSharp asynchronous?

The main purpose of RestSharp is to make synchronous and asynchronous calls to remote resources over HTTP.


3 Answers

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; 
like image 161
Funkel Avatar answered Sep 28 '22 00:09

Funkel


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;
like image 27
John Meyer Avatar answered Sep 27 '22 22:09

John Meyer


This worked fine for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
like image 22
Anjan Kant Avatar answered Sep 28 '22 00:09

Anjan Kant