Search code examples
c#apirestsharp

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?


Solution

  • 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