繁体   English   中英

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

[英]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#。

走出邮递员,我得到了一个有序......

{
  "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;

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM