Json Post 在 Postman 中有效,但在 C# 中无效

Fri*_*man 2 c# json restsharp

当我在 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);
Run Code Online (Sandbox Code Playgroud)

我试图用 postman-token、cache-control 删除行,但总是一样没有错误没有响应。(在响应中我应该得到访问令牌)

ajg*_*ajg 5

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

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

 public class Body
 {
    public string applicationKey { get; set; }
    public string userSecret { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

并将其作为参数内容传递

 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);
Run Code Online (Sandbox Code Playgroud)

原来是TLS版本问题。

通过添加固定

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
Run Code Online (Sandbox Code Playgroud)

在通话之前。