简体   繁体   English

500:尝试从C#控制台调用REST API时发生内部服务器错误

[英]500: internal server error while trying to call a REST api from C# console

I m trying to generate a token from salesforce api with oauth. 我正在尝试使用oauth从salesforce api生成令牌。 I m using this token to retreive data and then perform put request for each object. 我正在使用此令牌检索数据,然后对每个对象执行放置请求。 However, the web response is showing an unhandled exception saying "500:Internal server error" while im trying to generate a token. 但是,Web响应显示即时消息试图生成令牌时显示未处理的异常,提示“ 500:内部服务器错误”。 I need to pass content type and accept in header params and other params in body. 我需要传递内容类型并接受标头参数和正文中的其他参数。

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&username=user@username.com.test&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;
        }

Headers: Postman ; 标头: 邮递员 Application 应用

I believe the content your are passing in the body should be in the URL. 我相信您在正文中传递的内容应该在URL中。 The Developer Documentation suggests building your HttpWebRequest like this: 开发人员文档建议按以下方式构建您的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";

EDIT 编辑

Sorry, I spent a lot of time trying to get it working with the content in the body like you have it, but I kept getting "(400) Bad Request" as the response. 抱歉,我花了很多时间试图使它像您所拥有的那样与体内内容一起工作,但是我一直收到“(400)Bad Request”作为响应。 I'm not sure why you were originally getting "500:Internal server error" back; 我不确定为什么您最初会收到“ 500:Internal server error”(500:内部服务器错误)的信息; I kept getting the "(400) Bad Request" response back using the exact same code you were using. 我一直使用与您使用的完全相同的代码来获取“(400)Bad Request”响应。

The code example in the Developer Documentation is working for me. 开发人员文档中的代码示例对我有用。 There are some REST wrappers available if you would like to try that; 如果您想尝试一下,可以使用一些REST包装器。 most are available as NuGet packages. 大多数都可以通过NuGet软件包获得。 See SalesforceSharp . 请参阅SalesforceSharp It may be worth considering as it would likely reduce the amount of code you have to write and be less tedious. 可能值得考虑,因为这可能会减少您必须编写的代码量并且减少繁琐的工作。

Here is my source code which I copied from the Developer Documentation if you would like to replace it with your credentials and see if it works for you: 这是我的源代码,如果您想用您的凭据替换它,请从开发人员文档中复制并查看它是否适用:

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();
            }
        }
    }
}

Some things to consider: Since you ended up getting a "(400) Bad Request" when you initially tried the example code as opposed to the "500:Internal server error", the "HTTP 400" is more specific and usually indicates a syntax error, so it might be worth trying the example method again and making sure something wasn't mistyped, and your security token, site key, client secret, username, and password are correct, and that you appended your security token to the end of your password. 需要考虑的一些事情:由于您最初在尝试示例代码时遇到了“(400)错误请求”,而不是“ 500:内部服务器错误”,因此“ HTTP 400”更为具体,通常表示一种语法错误,因此值得再次尝试该示例方法,并确保没有输入错误的内容,并且您的安全令牌,站点密钥,客户端密钥,用户名和密码正确无误,并且将安全令牌附加到末尾你的密码。

Edit 2 编辑2

See how SalesforceSharp authenticates with Salesforce in Line 93 . 第93行中查看SalesforceSharp如何通过Salesforce进行身份验证。 They are using RestSharp, which is available as a NuGet package. 他们正在使用RestSharp,它可以作为NuGet软件包使用。

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

相关问题 更新一个问题以使用Rest API C#替换服务器并获得500 Internal Server Error - Update an issue to redmine server using Rest API C# and getting 500 Internal Server Error 500 px API与C#引发500内部服务器错误 - 500 px api with C# throwing 500 Internal Server Error 尝试在Visual Studio中从JavaScript调用插入值到SQL Server时出现内部服务器错误500 - Getting a internal server error 500 while trying to call insert values from javascript into sql server in visual studio Soap调用在c#中给出500(内部服务器错误) - Soap call gives 500 (internal server error) in c# C# Web API - 内部服务器错误 500 - C# Web API - Internal Server Error 500 当我尝试从.net(C#)中的`ektron`获取所有`groupid`时出现内部服务器错误500 - Internal server error 500 when I am trying to get all `groupid` from `ektron` in .net (c#) C#500内部服务器错误MongoDB - C# 500 Internal Server Error MongoDB 500内部服务器错误Unity C# - 500 Internal Server Error Unity C# 尝试在c#中获取页面源时给出(500)内部服务器错误 - When trying to get page source in c# gives (500) Internal Server Error 在 Web API 中使用异步等待时出现 500 内部服务器错误 - 500 internal server error while using async await in web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM