Friedlman Friedlman - 8 months ago 48
C# Question

Json Post works in Postman but not in C#

When I try the Post request in Postman it gives me the right response with no error. When I use the generated Restsharp code from Postman the response is always empty with no error.

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);


I tried to delete the lines with postman-token, cache-control but always the same no error no response. (In the response I should get the access token)

ajg ajg
Answer Source

But I also think you may have an issue as you are passing the body as JSON, and RestSharp will try to serialise it into JSON again. Try this.

Make a class to hold your parameters

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

and pass it as the parameter content

 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);

turned out it was TLS version issue.

Fixed by adding

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

before the call.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download