c# – 使用RESTSHARP时API返回错误

当使用RestSharp调用API时,我收到此错误:

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

我已经验证我的客户端ID,密码,用户名和密码是否正确.我能够在没有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();
}

使用RestSharp进行此操作时我错过了什么?

解决方法:

事实证明,因为这个调用是HTTPS我需要添加以下代码行

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
上一篇:C#-RestSharp异步后台线程


下一篇:c# – WP 7.1上的Restsharp添加cookie