RestSharp响应返回空

时间:2017-12-01 00:14:37

标签: c# rest

我正在使用RestSharp与UPS API通信。

我有POSTMAN,我可以和API交谈,但是当我把它移植到c#时,我得到一个空值来回复。内容。

private void button2_Click(object sender, EventArgs e)
        {
            label1.Text = CustomerName;
            MessageBox.Show(username);
            MessageBox.Show(password);
            MessageBox.Show(Lic);
            try
            {
                var client = new RestClient("https://wwwcie.ups.com/rest/Track");
                var request = new RestRequest(Method.POST);
                request.AddHeader("postman-token", "73a23cf5-558a-9a83-ec80-4a224b35351a");
                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("content-type", "application/json");
                request.AddParameter("application/json", "{\r\n  \"UPSSecurity\": {\r\n    \"UsernameToken\": {\r\n      \"Username\": " + username + ",\r\n      \"Password\": " + password + "\r\n    },\r\n    \"ServiceAccessToken\": {\r\n      \"AccessLicenseNumber\": " + Lic + "\r\n    }\r\n  },\r\n  \"TrackRequest\": {\r\n    \"Request\": {\r\n      \"RequestAction\": \"Track\",\r\n      \"RequestOption\": \"activity\"\r\n    },\r\n    \"InquiryNumber\": " + textBox1.Text.Trim() + "\r\n  }\r\n}", ParameterType.RequestBody);
                string result = "";
                request.Timeout = 10000;
                //IRestResponse response = client.Execute(request);

                client.ExecuteAsync(request, (response) =>
                {
                    result = response.Content;
                   MessageBox.Show(result);
                }
                );
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
        }

一切看起来都不错,但我不确定我遇到问题的地方,我浏览了过去的文章并注意到ExecuteAsync,所以我尝试了解决方案,但它仍然是空的。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

我添加了这个并且它完成了这个技巧。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

答案 1 :(得分:0)

由于某种原因,当我的目标框架是.net 4.5.2而不是.net 4.7.1时,我遇到了这个问题。对于4.5.2 losrob答案为我工作。看起来这与两个框架版本之间的默认安全协议有所不同。最好使用| =这样的代码编写代码:

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

这将允许SecurityProtocol默认设置的默认设置在以后的框架版本更新默认设置时保留。参见另一篇Default SecurityProtocol in .NET 4.5