163

I am trying to make a very basic REST call to my MVC 3 API and the parameters I pass in are not binding to the action method.

Client

var request = new RestRequest(Method.POST);

request.Resource = "Api/Score";
request.RequestFormat = DataFormat.Json;

request.AddBody(request.JsonSerializer.Serialize(new { A = "foo", B = "bar" }));

RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Server

public class ScoreInputModel
{
   public string A { get; set; }
   public string B { get; set; }
}

// Api/Score
public JsonResult Score(ScoreInputModel input)
{
   // input.A and input.B are empty when called with RestSharp
}

Am I missing something here?

7 Answers 7

259

You don't have to serialize the body yourself. Just do

request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body

If you just want POST params instead (which would still map to your model and is a lot more efficient since there's no serialization to JSON) do this:

request.AddParameter("A", "foo");
request.AddParameter("B", "bar");
14
  • 4
    Both. The second approach is much faster though. Jun 11, 2011 at 0:32
  • 5
    You can do AddObject(new { A = "foo", B = "bar" }) too which takes the object properties and converts them into parameters Jun 11, 2011 at 3:33
  • 70
    For those that want to jsonize themselves: request.AddParameter("text/json", body, ParameterType.RequestBody); Mar 2, 2013 at 0:58
  • 1
    @KylePatterson you can also implement your own ISerializer and set RestClient.JsonSerializer to use it. Mar 21, 2013 at 2:11
  • 2
    There's one obsolete parantheses after the request.AddBody(new ... in your first example.
    – Benjamin
    Jul 15, 2014 at 7:47
68

In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:

request.AddJsonBody(new { A = "foo", B = "bar" });

This method sets content type to application/json and serializes the object to a JSON string.

4
  • 3
    How to attach file to this request?
    – POV
    Jul 23, 2017 at 19:49
  • 1
    how do you name the object? eg. if you need to send "details" : { "extra" : "stuff" } ?
    – mdegges
    Feb 8, 2018 at 0:50
  • @OPV You can add a file to the request like this: request.AddFile(pathToTheFile); Feb 9, 2018 at 1:31
  • 1
    @mdegges If you are using an anonymous class as the body to have the JSON look like your example setup the RestSharp Request like this: var client = new RestSharp.RestClient("http://your.api.com"); var request = new RestSharp.RestRequest("do-something", Method.POST); var body = new {details = new {extras = "stuff"}}; request.AddJsonBody(body); var response = client.Execute(request); Feb 9, 2018 at 2:19
51

This is what worked for me, for my case it was a post for login request :

var client = new RestClient("http://www.example.com/1/2");
var request = new RestRequest();

request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", body , ParameterType.RequestBody);

var response = client.Execute(request);
var content = response.Content; // raw content as string  

body :

{
  "userId":"[email protected]" ,
  "password":"welcome" 
}
3
  • 3
    How do you insert the body into your c# code ? as string body = "{ "userId":"[email protected]" , "password":"welcome" }"; does not work.
    – Kynao
    Jul 19, 2018 at 18:51
  • 1
    You should use "" instead of " string body = @" { ""userid"", ... " Aug 5, 2019 at 7:32
  • If I have " var myJSON = "{ JSON Content }" , then what changes I have to make in AddParameters ?
    – blac040
    Mar 21, 2022 at 13:25
15

Hope this will help someone. It worked for me -

RestClient client = new RestClient("http://www.example.com/");
RestRequest request = new RestRequest("login", Method.POST);
request.AddHeader("Accept", "application/json");
var body = new
{
    Host = "host_environment",
    Username = "UserID",
    Password = "Password"
};
request.AddJsonBody(body);

var response = client.Execute(request).Content;
1
  • Looks like request.AddHeader("Accept", "application/json"); is the correct answer. Oct 3, 2019 at 8:31
0

If you have a List of objects, you can serialize them to JSON as follow:

List<MyObjectClass> listOfObjects = new List<MyObjectClass>();

And then use addParameter:

requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));

And you wil need to set the request format to JSON:

requestREST.RequestFormat = DataFormat.Json;
0

You might need to Deserialize your anonymous JSON type from the request body.

var jsonBody = HttpContext.Request.Content.ReadAsStringAsync().Result;
ScoreInputModel myDeserializedClass = JsonConvert.DeserializeObject<ScoreInputModel>(jsonBody);
-3

Here is complete console working application code. Please install RestSharp package.

using RestSharp;
using System;

namespace RESTSharpClient
{
    class Program
    {
        static void Main(string[] args)
        {
        string url = "https://abc.example.com/";
        string jsonString = "{" +
                "\"auth\": {" +
                    "\"type\" : \"basic\"," +
                    "\"password\": \"@P&p@y_10364\"," +
                    "\"username\": \"prop_apiuser\"" +
                "}," +
                "\"requestId\" : 15," +
                "\"method\": {" +
                    "\"name\": \"getProperties\"," +
                    "\"params\": {" +
                        "\"showAllStatus\" : \"0\"" +
                    "}" +
                "}" +
            "}";

        IRestClient client = new RestClient(url);
        IRestRequest request = new RestRequest("api/properties", Method.POST, DataFormat.Json);
        request.AddHeader("Content-Type", "application/json; CHARSET=UTF-8");
        request.AddJsonBody(jsonString);

        var response = client.Execute(request);
        Console.WriteLine(response.Content);
        //TODO: do what you want to do with response.
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.