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

C#REST API调用-在Postman中工作,而不是在代码中,c#,rest,salesforce,httpwebrequest,C#,Rest,Salesforce,Httpwebrequest,我有一些正在运行的现有代码,但突然退出了 我不明白为什么 这是我的密码: 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_s

我有一些正在运行的现有代码,但突然退出了

我不明白为什么

这是我的密码:

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内部服务器错误
,在这之前,它工作得很干净

当我尝试使用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
,我收到了以下回复(以邮递员的形式):


有什么想法吗?

因此,答案是Salesforce终止了对TLS 1.0的支持,这是.NET 4.5中的默认版本

在这个链接中,他们提到这应该发生在2017年7月,但不知怎的,它提前击中了我们的实例。

我们后来确认它将在.NET4.6中工作,但在4.5中不工作

事实证明.NET4.6默认使用TLS1.2

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

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

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
希望这能帮助其他人解决同样的问题


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

你确定方法类型应该是“POST”吗?@levent-是的,我在《邮差》中也使用了这种方法。。。GET不起作用。postman成功案例中的request.contentType是什么?@levent-适用于postman中的任何内容类型<代码>表单数据,
x-www-form-urlencoded
原始
,或
二进制
谢谢你救了我。希望我能多投票一次。你在哪里添加了这一行?对我来说,就在主程序的开头。这不是专门针对salesforce的。我在这个问题上挣扎了好几个小时,终于结结巴巴地讨论了这个解决方案。升级到.NET4.6也很有效,谢谢。!
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;