API is returning error when using RESTSHARP

帅比萌擦擦* 提交于 2020-07-18 09:03:23

问题


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:


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;



回答2:


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;



回答3:


This worked fine for me:

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


来源:https://stackoverflow.com/questions/48549161/api-is-returning-error-when-using-restsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!