Arashsoft
Arashsoft

Reputation: 1

Use POST method in RestSharp

I want to use RestSharp to post data to my API here:

creat.php

My structure is like this:

read.php

In PostMan I use body option and raw input like this:

{
    "story_code" : "Amazing Pillow 2.0",
    "master_code" : "199",
    "created" : "2018-06-01 00:35:07"
}

PostMan

And it works. In RestSharp I used this code but it returned Bad Request and the message: "Unable to create product. Data is incomplete."

var client = new RestClient("http://api.dastanito.ir");
var request = new RestRequest("/storiesmaster/creat.php", Method.POST);

request.AddParameter("story_code", "value");
request.AddParameter("master_code", "value2");

IRestResponse response = client.Execute(request);
var content = response.Content;

I even used AddQueryParameter but again bad request.

What function should I use?

Upvotes: 0

Views: 13927

Answers (1)

steve16351
steve16351

Reputation: 5812

Instead of .AddParameter you could use AddJsonBody to get something similar to what Postman sent which you already know works fine.

The code below works for example:

var client = new RestClient("http://api.dastanito.ir");
var request = new RestRequest("/storiesmaster/creat.php", Method.POST);

request.AddJsonBody(new
{
    story_code = "value",
    master_code = "value2"
});

IRestResponse response = client.Execute(request);
var content = response.Content; // {"message":" created."}

If you inspect the outgoing message with Fiddler, it looks like this:

{"story_code":"value","master_code":"value2"}

Whereas your message using AddParameter looks like this:

story_code=value&master_code=value2

Upvotes: 5

Related Questions