使用RESTSHARP时,API返回错误

24
当使用RestSharp调用API时,我遇到了以下错误: “底层连接已关闭:发生了发送的意外错误。” 我已验证我的客户端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时,我错过了什么?


看看Fiddler中的这个请求,再看看你从Powershell发出的请求。比较一下两者之间的区别,找出需要更改的地方。 - user47589
3个回答

47

原来因为这个调用是HTTPS,所以我需要添加以下代码行:

所以结果表明,由于此调用是HTTPS,我需要添加以下代码行

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

1
将安全协议添加到tls12中解决了该问题。 - Shyam Narayan

11

对于 .Net 3.5 和 4.0 版本,您可以在初始化 RestSharp 客户端之前尝试添加此行代码:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;

这真是太神奇了,在经历了如此令人沮丧的探索期后!必须包括 .net framework 4.0(可能也包括3.5),无论是 RestSharp 客户端还是 Web 客户端! - sanrns

2

这对我来说很有效:

最初的回答:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接