2017-07-19 44 views
0

我尝试使用oauth从salesforce API生成令牌。我使用这个标记来检索数据,然后对每个对象执行放置请求。但是,当我尝试生成令牌时,Web响应显示出未处理的异常,并显示“500:内部服务器错误”。我需要传递内容类型并接受头部参数和其他参数。500:尝试从C#控制台调用REST API时出现内部服务器错误

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      string response = Post("https://xx-dev.cs15.my.salesforce.com/services/oauth2/token"); 
      dynamic data = JObject.Parse(response); 
      string accessToken = data.access_token; 


     } 
     //POST to generate token. 
     private static string Post(string url) 
     { 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
      request.Method = "POST"; 
      request.Accept = "application/json"; 
      request.ContentType = "application/x-www-form-urlencoded"; 
      string body = "client_id=43nmbmn43534y98jh_3yQty7vm3CqYMvrSdfdsfFDSGFW7kNYk_bWxmhTaY5KT&client_secret=123456789&grant_type=password&[email protected]&password=TestPassword"; 
      byte[] byteArray = Encoding.UTF8.GetBytes(body); 
      request.ContentLength = byteArray.Length; 

      Stream dataStream = request.GetRequestStream(); 
      dataStream.Write(byteArray, 0, byteArray.Length); 
      dataStream.Close(); 
      WebResponse response = request.GetResponse();//**I'm getting the error here** 
      dataStream = response.GetResponseStream(); 
      StreamReader reader = new StreamReader(dataStream); 
      string responseFromServer = reader.ReadToEnd(); 
      reader.Close(); 
      dataStream.Close(); 
      response.Close(); 

      return responseFromServer; 
     } 

接头: Postman; Application

+0

500响应通常表示您的请求有问题。尝试查看代理中的原始响应,例如提琴手,看看是否有任何额外的信息,这将有助于你。 – stuartd

+0

提供关于@stuartd建议的错误的更多详细信息 – Panciz

+0

@Jr Dev,我在下面更新了我的答案。另外我忘了提及,我想知道您的Salesforce配置是否针对您使用的帐户的API请求进行了设置,以防这是第一次将此帐户用于与API集成。 – Poosh

回答

-1

我相信你在正文中传递的内容应该在URL中。该Developer Documentation提出构建HttpWebRequest这样的:

string strContent = "grant_type=password" + 
"&client_id=" + consumerKey + 
"&client_secret=" + consumerSecret + 
"&username=" + acctName + 
"&password=" + acctPw; 

string urlStr = "https://login.salesforce.com/services/oauth2/token?" + strContent; 

HttpWebRequest request = WebRequest.Create(urlStr) as HttpWebRequest; 
request.Method = "POST"; 

编辑

对不起,我花了很多时间试图把它与身体就像你拥有了它的内容的工作,但我一直获得“(400)错误请求”作为回应。我不确定你为什么最初得到“500:内部服务器错误”;我一直使用与您使用的完全相同的代码获得“(400)错误请求”响应。

开发人员文档中的代码示例正在为我工​​作。如果你想尝试一下,有一些REST包装器可用;大多数都可以作为NuGet包使用。请参阅SalesforceSharp。这可能是值得考虑的,因为它可能会减少您必须编写的代码量并且不那么繁琐。

下面是我从Developer Documentation复制的,如果你想与您的凭据来取代它,看看我的源代码,如果你的作品:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Net; 
using System.Runtime.Serialization; 
using System.Runtime.Serialization.Json; 

namespace VerifyRESTTest 
{ 
    class Program 
    { 
     // Class used for serializing the OAuth JSON response 
     [DataContract] 
     public class OAuthUsernamePasswordResponse 
     { 
      [DataMember] 
      public string access_token { get; set; } 
      [DataMember] 
      public string id { get; set; } 
      [DataMember] 
      public string instance_url { get; set; } 
      [DataMember] 
      public string issued_at { get; set; } 
      [DataMember] 
      public string signature { get; set; } 
     } 

     private static string accessToken = ""; 
     private static string instanceUrl = ""; 

     private static void login() 
     { 
      string acctName = "########@gmail.com"; 
      string acctPw = "##############"; 
      string consumerKey = "###############################################"; 
      string consumerSecret = "#################"; 

      // Just for testing the developer environment, we use the simple username-password OAuth flow. 
      // In production environments, make sure to use a stronger OAuth flow, such as User-Agent 
      string strContent = "grant_type=password" + 
       "&client_id=" + consumerKey + 
       "&client_secret=" + consumerSecret + 
       "&username=" + acctName + 
       "&password=" + acctPw; 

      string urlStr = "https://############-dev-ed.my.salesforce.com/services/oauth2/token?" + strContent; 

      HttpWebRequest request = WebRequest.Create(urlStr) as HttpWebRequest; 
      request.Method = "POST"; 

      try 
      { 
       using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
       { 
        if (response.StatusCode != HttpStatusCode.OK) 
         throw new Exception(String.Format(
          "Server error (HTTP {0}: {1}).", 
          response.StatusCode, 
          response.StatusDescription)); 

        // Parse the JSON response and extract the access token and instance URL 
        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(OAuthUsernamePasswordResponse)); 
        OAuthUsernamePasswordResponse objResponse = jsonSerializer.ReadObject(response.GetResponseStream()) as OAuthUsernamePasswordResponse; 
        accessToken = objResponse.access_token; 
        instanceUrl = objResponse.instance_url; 
       } 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("\nException Caught!"); 
       Console.WriteLine("Message :{0} ", e.Message); 
      } 
     } 

     static void Main(string[] args) 
     { 
      login(); 
      if (accessToken != "") 
      { 
       // display some current login settings 
       Console.Write("Instance URL: " + instanceUrl + "\n"); 
       Console.Write("Access Token: " + accessToken + "\n"); 
       Console.Write("Press any key to continue:\n"); 
       Console.ReadKey(); 
      } 
     } 
    } 
} 

有些事情要考虑:既然你最终得到当您最初尝试示例代码而不是“500:内部服务器错误”时,“(400)错误请求”,“HTTP 400”更具体,通常表示语法错误,因此可能值得尝试示例方法,并确保某些内容没有输入错误,并且您的安全令牌,站点密钥,客户端密码,用户名和密码都是正确的,并且您将安全令牌附加到密码末尾。

编辑2

Line 93 SalesforceSharp与Salesforce如何验证。他们正在使用RestSharp,它可以作为NuGet包使用。

+0

https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm&language=en&type=0 –

+0

@LB,我引用了Salesforce开发人员文档中提供的C#代码(请参阅我的答案中的链接)以获取访问权限令牌。我看不出有什么问题。 – Poosh

+0

尝试使用更改的网址,但现在我得到400的错误响应:错误的请求 –

相关问题