【问题标题】:An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user codeSystem.dll 中出现“System.Net.WebException”类型的异常,但未在用户代码中处理
【发布时间】:2014-01-06 11:06:56
【问题描述】:

我正在尝试从 Visual Studio 访问 Salesforce 数据。但是代码返回了上述异常。 我的类文件如下。

     public string HttpPost(string URI, string Parameters)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";

            // Add parameters to post
            byte[] data = System.Text.Encoding.ASCII.GetBytes(Parameters);
            req.ContentLength = data.Length;
            System.IO.Stream os = req.GetRequestStream();
            os.Write(data, 0, data.Length);
            os.Close();

            // Do the post and get the response.
             **System.Net.WebResponse resp = req.GetResponse();**
                if (resp == null) return null;
                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                return sr.ReadToEnd().Trim();
 }

我正在尝试调用 POST 方法以从 salesforce 检索令牌。 '**' 括起来的语句会引发异常。

远程服务器返回错误:(400) Bad Request。

任何帮助表示赞赏。

【问题讨论】:

  • 捕获异常并查看响应正文,它将获得有关请求失败原因的更多信息。除非您提供正在使用的 URI 和参数值,否则很难说明为什么它可能不起作用。

标签: asp.net salesforce visual-studio-2013


【解决方案1】:

完全不清楚您尝试发布到 Salesforce 的数据或您使用的 URL。这是您尝试向其提交数据的自定义 Web 服务还是类似 web 2 领导的东西?

将 Salesforce 与 .NET 集成的一种相当标准的方法是通过Partner API or the Enterprise API。这些通常是很好的起点,并且已经定义了 WSDL,您可以将它们作为 Web 参考导入到 Visual Studio 项目中。

还有各种REST apis。既然你发帖到

“login.salesforce.com/services/oauth2/token”

我假设您使用 Web Server OAuth 2 Authentication Flow 并且您拥有现在用来请求访问令牌的授权代码。

您发布到此 URL 的参数应类似于(注意,这是直接从 Salesforce 数据中获取的,因此不应包含任何敏感信息):

grant_type=authorization_code&code=aPrxsmIEeqM9PiQroGEWx1UiMQd95_5JUZ VEhsOFhS8EVvbfYBBJli2W5fn3zbo.8hojaNW_1g%3D%3D&client_id=3MVG9lKcPoNI NVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCs cA9GE&client_secret=1955279925675241571& redirect_uri=https%3A%2F%2Fwww.mysite.com%2Fcode_callback.jsp

您将需要使用 Salesforce 在上一步中返回给您的授权代码以及您自己的 client_id 和 client_secret。也可以随意设置redirect_uri。


使用用户名和密码建立 REST 连接:Understanding the Username-Password OAuth Authentication Flow

您需要将grant_type 设置为密码并提供用户名和密码。这应该发布到https://login.salesforce.com/services/oauth2/token

grant_type=password&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82Hn FVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&client_secret= 1955279925675241571&用户名=testuser%40salesforce.com&密码=mypassword123456

然后您可以从响应中获取access_token

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多