【问题标题】:Json Post works in Postman but not in C#Json Post 在 Postman 中工作,但不在 C# 中
【发布时间】:2017-08-17 08:23:34
【问题描述】:

当我在 Postman 中尝试 Post 请求时,它给了我正确的响应,没有错误。当我使用 Postman 生成的 Restsharp 代码时,响应始终为空且没有错误。

var client = new RestClient("https://myurl/api/authenticate/authenticate");
        var request = new RestRequest(Method.POST);
        request.AddHeader("postman-token", "00497e4f-f58f-677d-f98a-bb972032c2eb");
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("content-type", "application/json");
        request.AddParameter("application/json", "{\n\t\"applicationKey\" : \"MYAPPLICATIONKEY\",\n\t\"userSecret\" : \"MYUSERSECRET\"\n}", ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);
        Console.WriteLine(response.Content);

我尝试删除带有 postman-token、缓存控制的行,但始终相同,没有错误没有响应。 (在响应中我应该得到访问令牌)

【问题讨论】:

  • 您使用自己的服务器证书吗?

标签: c# json restsharp


【解决方案1】:

但我也认为您将正文作为 JSON 传递时可能会遇到问题,RestSharp 将尝试再次将其序列化为 JSON。试试这个。

创建一个类来保存你的参数

 public class Body
 {
    public string applicationKey { get; set; }
    public string userSecret { get; set; }
 }

并将其作为参数内容传递

 var client = new RestClient("https://myurl");
 var request = new RestRequest(Method.POST);  
 request.RequestFormat = DataFormat.Json;
 request.Resource = "api/authenticate/authenticate";

 var body = new Body();
 body.applicationKey = "MYAPPLICATIONKEY";
 body.userSecret = "MYUSERSECRET";

 request.AddBody(body);
 IRestResponse response = client.Execute(request);
 Console.WriteLine(response.Content);

原来是 TLS 版本问题。

通过添加修复

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

通话前。

【讨论】:

  • 还是一样,没有任何响应。内容和没有错误消息....我应该在某处添加 charset=UTF-8 吗?
  • 我会使用 Fiddler (telerik.com/fiddler) 查看您的请求和响应,看看您是否能发现任何东西。您应该可以很容易地找到在线使用 Fiddler 的指南。
  • 好的,我把我的代码放在那里,它给了我这个错误: {"Cause":"Unable to execute the REST operation","Detail":"java.lang.IllegalArgumentException: Unable to parse the给定输入流作为 JSON 文档
  • 你能试试我上面的编辑吗,那是从我的代码中得到的,它确实有效
  • 好的,我已经把它放入小提琴中,我收到一个 html 错误“无法处理请求...请求服务不存在”
【解决方案2】:

你可以试试这个只是为了测试:

 public static void Main(string[] args)
 {
     ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
            {
               return true;
            };
     //...
     //Your Rest Call
 }

对于内部使用,您可以这样做:

ServicePointManager.ServerCertificateValidationCallback +=  (sender, cert, chain, error) =>
{
     return cert.GetCertHashString() == "server certificate hash";
};

【讨论】:

  • 如果你使用控制台应用程序然后在 main
  • 我在 IrestResponse 和 Console.Writeline 之间复制了这个,但是当我调试它时它只是相同的空消息
  • 它必须在你的 restserver 调用之前
  • IRestResponse response = client.Execute(request);但把它放在 var client = new RestClient("myurl/api/authenticate/authenticate");
  • 还是一样没有消息没有(顺便感谢您的耐心和帮助)
猜你喜欢
  • 2015-11-08
  • 2021-02-16
  • 1970-01-01
  • 2020-05-26
  • 2019-12-27
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多