RestSharp JSON Parameter Posting

Wesley Tansey picture Wesley Tansey · Jun 11, 2011 · Viewed 198.6k times · Source

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?

Answer

John Sheehan picture John Sheehan · Jun 11, 2011

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

request.RequestFormat = DataFormat.Json;
request.AddBody(new { A = "foo", B = "bar" }); // uses JsonSerializer

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