【发布时间】:2019-06-15 21:33:28
【问题描述】:
感谢您提供任何帮助。我只是尝试对 Oauth 用户名-密码流进行基本调用。当我尝试调用 GetResponse() 时,它给了我一个错误的请求 (400) 错误。
string sessionId = String.Empty;
string url = ConfigurationManager.AppSettings["SfdcLoginUrl"].ToString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://test.salesforce.com/services/oauth2/token");
request.Method = "POST";
request.ContentType = "application/json";
StringBuilder sb = new StringBuilder();
sb.Append("grant_type=password&");
sb.Append("client_id=" + ConfigurationManager.AppSettings["ClientId"].ToString() + "&");
sb.Append("client_secret=" + ConfigurationManager.AppSettings["ClientSecret"].ToString() + "&");
sb.Append("username=" + HttpUtility.UrlPathEncode(username) + "&");
sb.Append("password=" + HttpUtility.UrlPathEncode(password));
System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(sb.ToString());
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
sessionId = reader.ReadToEnd();
【问题讨论】:
-
您发送的内容类型为 json,但您没有发送 json。
-
抱歉,我应该指定的。将内容类型更改为“application/x-www-form-urlencoded”也会产生相同的错误。这只是我(此时有点盲目)摆弄的结果
-
您没有对 clientId 或密码进行编码。同样,当您查看响应正文 400 时,会有更多信息
-
刚刚清理了这篇文章。总之,事实证明,这种类型的请求需要位于将 SalesForce 域列入白名单的域/框上,或者在密码末尾包含用户安全令牌。谢谢,superfell,您在这里的见解 - 非常感谢!
-
如果您能够回答自己的问题,请将解决方案作为答案发布。
标签: c# rest oauth salesforce