Friedlman
Friedlman

Reputation: 87

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)

Upvotes: 2

Views: 8486

Answers (2)

ajg
ajg

Reputation: 1753

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.

Upvotes: 5

Ive
Ive

Reputation: 1331

You can try this only for test:

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

For internal usage, you can do:

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

Upvotes: 1

Related Questions