C# REST API 调用 - 在 Postman 中工作,而不是在代码中

C# REST API Call - Working in Postman, NOT in Code

我有一些可用的现有代码,但突然退出。

我不明白为什么...

这是我的代码:

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# 中不工作。

在 Postman 之外,我得到了一个有条不紊的...

{
  "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 中的默认设置。

在这个 link 中,他们提到这应该在 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;

希望对遇到同样问题的其他人有所帮助!

这么简单的单行解决方案需要几天时间才能找到,这有点令人沮丧。