2017-03-07 37 views
3

我有一些現有的代碼正在工作,並且突然退出。C#REST API調用 - 在Postman中工作,不在代碼中

我想不通爲什麼...

這裏是我的代碼:

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

爲了澄清,我已經試過,而不是一個POST要求GET,我會收到以下消息(在郵差):

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

這裏的任何想法?

+0

你確定方法類型應該是'POST'嗎? – levent

+0

@levent - 是的,這就是我在郵遞員中使用的... GET不起作用。 – gotmike

+0

什麼是postman成功案例中的request.contentType? – levent

回答

7

因此,最終答案是Salesforce終止了對TLS 1.0的支持,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; 

希望幫助別人同樣的問題!

當這樣一個簡單的單線解決方案需要幾天才能找到時,有點令人沮喪。

+0

謝謝你救了我。希望我可以多勞多得。 – Saurabh

+0

謝謝!!!!!!! – Gaspa79

+0

你在哪裏添加了這一行? –

相關問題