RestSharp JSON参数发布

我试图做一个非常基本的REST调用到我的MVC 3 API和我传入的参数不绑定到操作方法。

客户

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 } 

我在这里错过了什么?

你不必亲自序列化身体。 做就是了

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

如果你只是想要POST参数(它仍然映射到你的模型,并且因为没有序列化到JSON效率更高),请执行以下操作:

 request.AddParameter("A", "foo"); request.AddParameter("B", "bar"); 

这是对我来说,我的情况是一个login请求的post:

 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 

身体 :

 { "userId":"sam@company.com" , "password":"welcome" } 

在当前版本的RestSharp(105.2.3.0)中,可以使用以下方法将JSON对象添加到请求正文:

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

此方法将内容types设置为application / json,并将对象序列化为JSONstring。