【问题标题】:C# REST API Call - Working in Postman, NOT in CodeC# REST API 调用 - 在 Postman 中工作,而不是在代码中
【发布时间】:2018-08-22 09:35:30
【问题描述】:

我有一些现有的代码正在运行并且突然退出。

我不知道为什么......

这是我的代码:

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"
}

这里有什么想法吗?

【问题讨论】:

  • 你确定方法类型应该是 'POST' 吗?
  • @levent - 是的,这也是我在 Postman 中使用的...... GET 不起作用。
  • 邮递员成功案例中的 request.contentType 是什么?
  • @levent - 适用于 Postman 中的任何内容类型。 form-datax-www-form-urlencodedrawbinary

标签: c# rest salesforce httpwebrequest


【解决方案1】:

因此,最终答案是 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;

希望能帮助遇到同样问题的其他人!

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

【讨论】:

  • 谢谢你救了我。希望我能多次投票。
  • 你在哪里添加了这一行?
  • 对我来说,就在主程序的开头附近。
  • 它不是特定于销售人员的。当最终绊倒这个解决方案时,我已经为这个问题苦苦挣扎了很多小时。并且它可以升级到 .NET 4.6,谢谢。!
猜你喜欢
  • 2018-06-26
  • 1970-01-01
  • 2021-09-13
  • 2020-05-01
  • 2016-12-25
  • 1970-01-01
  • 2023-04-08
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多