C#REST API调用 – 在邮递员中工作,而不是在代码中工作

我有一些现有的代码正在工作,并且突然退出。

我无法弄清楚为什么……

这是我的代码:

public static string RequestToken(string u, string pw) { string result = string.Empty; string strUrl = "https://xxx.cloudforce.com/services/oauth2/token?grant_type=password&client_id=XXXX&client_secret=XXXX&username=" + u + "&password=" + pw; HttpWebRequest tokenRequest = WebRequest.Create(strUrl) as HttpWebRequest; Debug.Print(strUrl); tokenRequest.Method = "POST"; try { using (HttpWebResponse tokenResponse = tokenRequest.GetResponse() as HttpWebResponse) { if (tokenResponse.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", tokenResponse.StatusCode, tokenResponse.StatusDescription)); DataContractJsonSerializer jsonSerializer2 = new DataContractJsonSerializer(typeof(ResponseAuthentication)); object objTokenResponse = jsonSerializer2.ReadObject(tokenResponse.GetResponseStream()); ResponseAuthentication jsonResponseAuthentication = objTokenResponse as ResponseAuthentication; result = jsonResponseAuthentication.strAccessToken; } } catch (Exception ex) { Debug.Print(ex.InnerException.ToString()); } return result; } 

我现在得到一个500 Internal Server Error ,在此之前干净利落。

当我尝试使用Postman进行调试时,我直接传递了URL,它工作正常。 即使我在代码中停止使用完全相同的URL然后从代码内部失败,它也适用于Postman,但不适用于C#。

走出邮递员,我得到了有序……

 { "access_token": "XXXXXX", "instance_url": "https://xxx.cloudforce.com", "id": "https://login.salesforce.com/id/XXXXXX", "token_type": "Bearer", "issued_at": "XXXXXX", "signature": "XXXXXX" } 

为了澄清,我尝试了一个GET请求而不是POST ,我收到了以下响应(在Postman中):

 { "error": "invalid_request", "error_description": "must use HTTP POST" } 

这里有什么想法?

因此,答案最终是Salesforce结束了对TLS 1.0的支持,这是.NET 4.5的默认设置。

在这个链接中,他们提到这应该发生在2017年7月,但不知何故,它提前击中了我们的实例。 https://help.salesforce.com/articleView?id=000221207&type=1

我们后来证实它可以在.NET 4.6中运行,但不适用于4.5 ……

原来.NET 4.6默认使用TLS 1.2。

这是一个非常简单的修复,花了很长时间才弄明白。

添加了这一行代码,它立即起作用:

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 

希望能帮助别人解决同样的问题!

当这样一个简单的单行解决方案需要数天才能找到时,有点令人沮丧。