RestSharp JSON参数发布

问题描述:

我想提出一个非常基本的REST调用到我的MVC 3 API和我通过在这些参数不会绑定到操作方法。

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.

客户端

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

服务器

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?

您不必自己序列化的身体。只要做到

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

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

如果你只是想POST PARAMS,而不是(这将仍然映射到你的模型和很多更有效,因为没有序列化到JSON)做到这一点:

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